【发布时间】:2020-05-13 14:20:53
【问题描述】:
我有一个使用matplotlib 创建的饼图,并且我使用波斯文本作为标签:
In [1]: import matplotlib.pyplot as plt
In [2]: from bidi.algorithm import get_display
In [3]: from arabic_reshaper import reshape
In [4]: labels = ["گروه اول", "گروه دوم", "گروه سوم", "گروه چهارم"]
In [5]: persian_labels = [get_display(reshape(l)) for l in labels]
In [6]: sizes = [1, 2, 3, 4]
In [7]: plt.rcParams['font.family'] = 'Sahel'
In [8]: plt.pie(sizes, labels=persian_labels, autopct='%1.1f%%')
In [9]: plt.savefig("pie.png", dpi=200)
结果如我所料:
现在我也想将百分比数字更改为波斯语。所以必须使用[۰, ۱, ۲, ۳, ۴, ۵, ۶, ۷, ۸, ۹],而不是[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]。
我可以很容易地用这样的函数把英文数字转换成波斯文:
def en_to_fa(text):
import re
mapping = {
'0': '۰',
'1': '۱',
'2': '۲',
'3': '۳',
'4': '۴',
'5': '۵',
'6': '۶',
'7': '۷',
'8': '۸',
'9': '۹',
'.': '.',
}
pattern = "|".join(map(re.escape, mapping.keys()))
return re.sub(pattern, lambda m: mapping[m.group()], str(text))
但我不知道如何将此函数应用于matplotlib 生成的百分比。有没有可能?
【问题讨论】:
标签: python matplotlib farsi