Python 可视化图表标题设置中文方法
在使用 Python 可视化库(如 matplotlib、seaborn 等)进行图形绘制时,可以通过以下步骤将图形标题设置为中文:
- 导入中文字体库
在代码开头,导入中文字体库,如下所示:
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf', size=14)
其中,fname 参数指定中文字体库的路径,size 参数指定字体大小。
- 设置中文标题
在绘制图形时,通过 plt.title() 函数设置图形标题,并指定字体为中文字体库,如下所示:
plt.title('中文标题', fontproperties=font)
其中,fontproperties 参数指定字体为中文字体库。
完整示例代码:
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf', size=14)
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.xlabel('X轴', fontproperties=font)
plt.ylabel('Y轴', fontproperties=font)
plt.title('中文标题', fontproperties=font)
plt.show()
原文地址: https://www.cveoy.top/t/topic/omzS 著作权归作者所有。请勿转载和采集!