【问题标题】:Using Persian numbers in pie charts of matplotlib在 matplotlib 的饼图中使用波斯数字
【发布时间】: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


    【解决方案1】:

    您可以为autopct 传入一个函数,而不仅仅是一个字符串格式化程序。所以基本上,您只需将您的en_to_fa 传递给autopct,并进行一些小的修改:您只需首先将您的数字转换为具有适当数字格式的字符串,然后进行语言转换。我的机器不是为波斯语设置的,但以下演示了该方法(将数字映射到字母表的前 10 个字母):

    import matplotlib.pyplot as plt
    
    def num_to_char(num, formatter='%1.1f%%'):
        num_as_string = formatter % num
        mapping = dict(list(zip('0123456789.%', 'abcdefghij.%')))
        return ''.join(mapping[digit] for digit in num_as_string)
    
    sizes = range(1, 5)
    plt.pie(sizes, autopct=num_to_char)
    plt.savefig("pie.png", dpi=200)
    

    【讨论】:

    • 有没有这种方法可以转换x-axis 中显示的日期?请查看我的question
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-17
    • 2017-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多