在使用Python的Matplotlib库进行数据可视化时,中文字符显示问题是一个常见挑战。以下是几种解决方案,以确保图表中的中文字符能够正确显示:
方法一:指定字体文件
思源黑体是由Adobe和Google合作推出的开源字体,适用于解决中文显示问题。你可以从以下链接下载字体文件:
- 官网:思源宋体
- GitHub地址:Source Han Sans
import numpy as np
from matplotlib import pyplot as plt
import matplotlib
# 指定字体文件路径
cn_font = matplotlib.font_manager.FontProperties(fname="SourceHanSansSC-Bold.otf")
x = np.arange(1, 13)
y = [-10.6, -7.9, -3.6, 1.5, 5.8, 10.9, 14.3, 13.9, 10.4, 2.5, -2.9, -7.9]
plt.title("某地月平均气温变化图", fontproperties=cn_font)
plt.xlabel("月份", fontproperties=cn_font)
plt.ylabel("单位:℃", fontproperties=cn_font)
plt.plot(x, y)
plt.show()
方法二:全局字体设置
通过修改Matplotlib的全局配置,可以设置默认字体。
import numpy as np
from matplotlib import pyplot as plt
import matplotlib as mpl
mpl.rcParams["font.family"] = "FangSong" # 设置全局字体为仿宋
mpl.rcParams["axes.unicode_minus"] = False # 确保负号显示正常
x = [str(i) + '月' for i in range(1, 13)]
y = [-10.6, -7.9, -3.6, 1.5, 5.8, 10.9, 14.3, 13.9, 10.4, 2.5, -2.9, -7.9]
plt.title("某地月平均气温变化图")
plt.xlabel("月份")
plt.ylabel("单位:℃")
plt.bar(x, y)
plt.show()
方法三:使用操作系统字体
如果你不想下载额外的字体文件,可以直接使用操作系统中的字体。
import numpy as np
from matplotlib import pyplot as plt
import matplotlib as mpl
from matplotlib.font_manager import FontProperties
mpl.rcParams["font.family"] = "FangSong"
mpl.rcParams["axes.unicode_minus"] = False
x = [str(i) + '月' for i in range(1, 13)]
y = [-10.6, -7.9, -3.6, 1.5, 5.8, 10.9, 14.3, 13.9, 10.4, 2.5, -2.9, -7.9]
font1 = FontProperties(fname=r"C:/Windows/Fonts/simhei.ttf") # 指定系统字体路径
plt.title("某地月平均气温变化图", fontproperties=font1, fontsize=16)
plt.bar(x, y)
plt.show()
查看系统字体
你可以通过以下代码列出系统中安装的所有字体。
from matplotlib import pyplot as plt
import matplotlib
a = sorted([f.name for f in matplotlib.font_manager.fontManager.ttflist])
for i in a:
print(i)
常用字体列表
以下是一些常用的中文字体,你可以根据需要选择:
- 宋体:SimSun
- 黑体:SimHei
- 微软雅黑:Microsoft YaHei
- 微软正黑体:Microsoft JhengHei
- 新宋体:NSimSun
- 新细明体:PMingLiU
- 细明体:MingLiU
- 标楷体:DFKai-SB
- 仿宋:FangSong
- 楷体:KaiTi
- 隶书:LiSu
- 幼圆:YouYuan
- 华文细黑:STXihei
- 华文楷体:STKaiti
- 华文宋体:STSong
- 华文中宋:STZhongsong
- 华文仿宋:STFangsong
- 方正舒体:FZShuTi
- 方正姚体:FZYaoti
- 华文彩云:STCaiyun
- 华文琥珀:STHupo
- 华文隶书:STLiti
- 华文行楷:STXingkai
- 华文新魏:STXinwei
方法四:通过fontdict参数设置
from matplotlib import pyplot as plt
import matplotlib as mpl
mpl.rcParams["font.family"] = "KaiTi"
mpl.rcParams["axes.unicode_minus"] = False
x = [str(i) + '月' for i in range(1, 13)]
y = [-10.6, -7.9, -3.6, 1.5, 5.8, 10.9, 14.3, 13.9, 10.4, 2.5, -2.9, -7.9]
plt.xlabel("月份", fontsize=12, fontdict={"family": "FangSong", "size": 15, "color": "r"})
plt.ylabel("单位:℃", fontsize=12, fontdict={"family": "KaiTi", "size": 15, "color": "r"})
plt.title("某地月平均气温变化图", fontsize=16, fontdict={"family": "SimHei", "size": 15, "color": "#000000"})
plt.bar(x, y)
plt.show()
参考文献: