Matplotlib: Writing right-to-left text (Hebrew, Arabic, etc.)

纵饮孤独 提交于 2019-12-18 14:34:34

问题


I'm trying to add some text to my plot which is RTL (in this case, Hebrew). After some work managed to get it to display the text, but it's displayed LTR (meaning, in the reverese order). I've dug into the reference and did extensive search online and nothing came up.

An example for what I'm using:

import matplotlib.pyplot as plt
plt.text(0.5, 0.5, u'שלום כיתה א', name = 'Arial')
plt.show()

and it displays 'א התיכ םלוש'. In case you can't see the Hebrew, it's as if i'd input 'Hello', and the output would be 'olleH'.

I can't simply reverse the input since it's mixed LTR and RTL.

Every help would be appreciated.


回答1:


For Arabic you need both bidi.algorithm.get_display and arabic_reshaper modules:

from bidi.algorithm import get_display
import matplotlib.pyplot as plt
import arabic_reshaper

reshaped_text = arabic_reshaper.reshape(u'لغةٌ عربيّة')
artext = get_display(reshaped_text)

plt.text(0.25, 0.45, artext , name = 'Times New Roman',fontsize=50)
plt.show()




回答2:


For whoever encounters the same problem, I found a partial solution.

The bidi package provides this functionality, so using:

from bidi import algorithm as bidialg
import matplotlib.pyplot as plt
text = bidialg.get_display(u'שלום כיתה א')
plt.text(0.5, 0.5, text , name = 'Arial')
plt.show()

displays it correctly.

So why is it partial? Because I found out that the bidi package sometimes messes up latex expression which I use with matplotlib. So use it carefully.




回答3:


I had the same issue and i think that using both answers of @Korem and @Nasser Al-Wohaibi like:

import arabic_reshaper
from bidi.algorithm import get_display

new_text=get_display(arabic_reshaper.reshape(old_text))

because only the arabic_reshaper didnt rearrange the letters and the bidi only didn't combine them

^_^



来源:https://stackoverflow.com/questions/15421746/matplotlib-writing-right-to-left-text-hebrew-arabic-etc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!