在Python中使用matplotlib绘制饼图时,如果遇到中文字符无法显示的问题,通常是因为matplotlib默认不支持中文显示。以下是解决这个问题的方法:
解决方案1:设置字体
在Python代码中添加以下语句来设置字体,以便支持中文字符显示:
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Simhei'] 设置字体为黑体
解决方案2:加载本地字体文件
如果系统中没有安装黑体字体,或者想要使用其他字体,可以通过以下步骤加载本地字体文件:
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf', size=14) 指定字体路径和大小
然后在绘制饼图时,将字体属性传递给相关函数:
plt.pie(sizes, labels=labels, autopct='%1.1f%%', textprops={'fontproperties': font})
请确保字体文件路径正确,并且字体文件已经被系统正确安装。
示例代码
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
设置字体属性
font = FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf', size=14)
饼图数据
sizes = [30, 70]
labels = ['A', 'B']
绘制饼图
plt.pie(sizes, labels=labels, autopct='%1.1f%%', textprops={'fontproperties': font})
设置标题
plt.title('饼图标题', fontproperties=font)
显示图像
plt.show()
请根据你的实际情况调整字体路径和大小。