发布时间:2024-03-21 15:30:02
Matplotlib 默认不支持中文字体,这因为 Matplotlib 只支持 ASCII 字符,但中文标注更加符合中国人的阅读习惯。因此,本节重点讲解如何在 Windows 环境下让 Matplotlib 显示中文。import matplotlib.pyplot as plt plt.rcParams["font.sans-serif"]=["SimHei"] #设置字体 plt.rcParams["axes.unicode_minus"]=False #该语句解决图像中的“-”负号的乱码问题将上述代码添加到您的绘图程序中,即可解决中文乱码的问题。这是一种非常灵活、便捷的解决方法。完整的程序代码如下:
#绘制折线图 import matplotlib.pyplot as plt plt.rcParams["font.sans-serif"]=["SimHei"] #设置字体 plt.rcParams["axes.unicode_minus"]=False #正常显示负号 year = [2017, 2018, 2019, 2020] people = [20, 40, 60, 70] #生成图表 plt.plot(year, people) plt.xlabel('年份') plt.ylabel('人口') plt.title('人口增长') #设置纵坐标刻度 plt.yticks([0, 20, 40, 60, 80]) #设置填充选项:参数分别对应横坐标,纵坐标,纵坐标填充起始值,填充颜色 plt.fill_between(year, people, 20, color = 'green') #显示图表 plt.show()
import matplotlib matplotlib.matplotlib_fname()输出结果:
D:\python\python37\lib\site-packages\matplotlib\mpl-data\matplotlibrc然后修改配置文件 matplotlibrc。打开配置文件后,找到以下信息:
#font.family: sans-serif
#font.serif: DejaVu Serif, Bitstream Vera Serif, Computer Modern Roman, New Century Schoolbook, Century Schoolbook L, Utopia, ITC Bookman, Bookman, Nimbus Roman No9 L, Times New Roman, Times, Palatino, Charter, serif
将上述配置项前面的#
去掉,并修改的配置项,如下所示:
font.family : Microsoft YaHei, sans-serif font.serif: Microsoft YaHei, DejaVu Serif, Bitstream Vera Serif, Computer Modern Roman, New Century Schoolbook, Century Schoolbook L, Utopia, ITC Bookman, Bookman, Nimbus Roman No9 L, Times New Roman, Times, Palatino, Charter, serif注意,由于版本问题,上述内容配置信息可能存在一些差异,请自动忽略。
C:\Windows\Fonts\Microsoft YaHei UI复制完成后,将字体粘贴至以下路径文件中:
D:\python\python37\lib\site-packages\matplotlib\mpl-data\fonts\ttf字体粘贴后会出现一个 MSYH.ttc 的字体文件,如下所示:
import matplotlib.pyplot as plt import numpy as np x = np.linspace(-8, 8, 1024) y1 = 0.618 * np.abs(x) - 0.8 * np.sqrt(64 - x ** 2) y2 = 0.618 * np.abs(x) + 0.8 * np.sqrt(64 - x ** 2) plt.plot(x, y1, color='r') plt.plot(x, y2, color='r') plt.title("我爱365工具网",fontsize=20,color="b") plt.show()输出结果如下: