You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Python2.7中Matplotlib绘制UTF-8阿拉伯标签遇UnicodeDecodeError

解决Python 2.7中Matplotlib显示阿拉伯语标签的UnicodeDecodeError问题

我之前踩过Python2.7编码的大坑,尤其是非拉丁语系文本在Matplotlib里的显示问题,咱们一步步来搞定:

1. 先搞定Unicode字符串的编码问题

Python2.7里不带u前缀的字符串是字节串(bytes),阿拉伯语字符是UTF-8编码的,直接用会触发ASCII解码错误。所以首先要把标签改成Unicode字符串

labels = [u'عشرة', u'عشرين', u'ثلاثين']

2. 给Matplotlib配置阿拉伯语字体

Matplotlib默认字体不包含阿拉伯语字符,得指定支持阿拉伯语的字体,你可以根据自己的系统选:

  • Windows:'Arial Unicode MS'
  • Linux:'Noto Naskh Arabic' 或者 'Amiri'
  • macOS:'SF Arabic'

在代码里添加全局字体配置:

import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'Noto Naskh Arabic'

如果系统没自带对应字体,也可以下载一个阿拉伯语TTF字体文件,用FontProperties指定路径加载:

from matplotlib.font_manager import FontProperties
arabic_font = FontProperties(fname='/path/to/your/arabic/font.ttf')
# 之后在annotate里加上fontproperties=arabic_font参数

3. 处理阿拉伯语从右到左的显示顺序

阿拉伯语是RTL(从右到左)语言,直接显示会导致字符顺序颠倒,得用arabic_reshaperpython-bidi库来调整:
先安装依赖:

pip install arabic-reshaper python-bidi

然后在代码里处理标签:

import arabic_reshaper
from bidi.algorithm import get_display

processed_labels = []
for label in labels:
    # 重塑阿拉伯语字符的形态
    reshaped_text = arabic_reshaper.reshape(label)
    # 调整为从右到左的显示顺序
    bidi_text = get_display(reshaped_text)
    processed_labels.append(bidi_text)

完整修复后的代码

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

# 配置阿拉伯语字体
plt.rcParams['font.family'] = 'Noto Naskh Arabic'

# 使用Unicode字符串定义标签
labels = [u'عشرة', u'عشرين', u'ثلاثين']
# 处理RTL显示逻辑
processed_labels = [get_display(arabic_reshaper.reshape(label)) for label in labels]

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(processed_labels[i], xy=(x[i], y[i]), xytext=(5, 2), 
                 textcoords='offset points', ha='right', va='bottom')
plt.show()

额外提醒

如果条件允许,建议直接升级到Python3——Python2.7的编码问题真的是历史遗留大坑,Python3默认UTF-8编码会省掉很多麻烦。

内容的提问来源于stack exchange,提问作者user3286053

火山引擎 最新活动