1

I am trying to display plots but the labels are in utf-8 Arabic, python2.7.

    import matplotlib.pyplot as plt
    labels = ['عشرة','عشرين','ثلاثين']
    #labels=['A','B','C']
    x = [10, 12,13]
    y = [10,20,30]
    plt.figure(figsize=(16, 16)) 
    for i in range(len(x)):
          plt.scatter(x[i],y[i])
          plt.annotate(labels[i],
                 xy=(x[i], y[i]),
                 xytext=(5, 2),
                 textcoords='offset points',
                 ha='right',
                 va='bottom')
    plt.show()

for the utf-8 (labels = ['عشرة','عشرين','ثلاثين']) I have error

UnicodeDecodeError: 'ascii' codec can't decode byte 0xd8 in position 0: ordinal not in range(128)

while it works fine when labels=['A','B','C'].

  • I have updated the matplotlib, by sudo pip install matplotlib --upgrade The utf-8 Arabic words appeared, although they appeared with inverse ordering "let to right" . Now I need to solve the inner word to appear from right to left! – user3286053 Apr 07 '18 at 15:05

1 Answers1

0

I solved my Arabic font problem. I would like to share the solution in case any one needs it.

0- Be sure that your matplotlib is of the ver 2.2

to check

import matplotlib

matplotlib.version

'0.98.0' % if this is the case, then you need to upgrade it

To upgrade

sudo pip install matplotlib --upgrade

1- Install bidi

sudo easy_install python-bidi

2- Install arabic_reshaper that will make the letters order from right to let

sudo pip install arabic_reshaper

3-Change your code as following

    #!/usr/bin/python2.7
    # -*- coding: utf-8 -*-
    from __future__ import unicode_literals
    import arabic_reshaper
    from bidi.algorithm import get_display
    import matplotlib.pyplot as plt
    labels = ['عشرة','عشرين','ثلاثين']
    x = [10, 12,13]
    y = [10,20,30]
    plt.figure(figsize=(16, 16)) 
    for i in range(len(x)):
          a=arabic_reshaper.reshape(labels[i])
          aa = get_display(a)
          plt.scatter(x[i],y[i])
          plt.annotate(aa,
                  xy=(x[i], y[i]),
                  xytext=(5, 2),
                  textcoords='offset points',
                  ha='right',
                  va='bottom')
    plt.show()

For more information, https://matplotlib.org/faq/troubleshooting_faq.html

https://matplotlib.org/users/dflt_style_changes.html?highlight=changes%20default%20style

Print Arabic words from Python to ESC/POS printer?

http://mpcabd.xyz/python-arabic-text-reshaper/

Thanks