python中调用matplotlib画图,中文标注乱码强力解决办法
关于python中调用matplotlib画图,中文标注乱码
如下:
解决办法:
# 通用字体设置
from matplotlib import font_manager
# my_font = font_manager.FontProperties(fname="字体路径")
my_font = font_manager.FontProperties(fname="/Library/Fonts/Songti.ttc")
...
# 使用方法
plt.xlabel("内容描述",fontproperties=my_font)
实例: matplotlib折线图及中文标注显示
from matplotlib import pyplot as plt
import random
# windows 和linux设置字体的方法
# import matplotlib
# font = {'family' : 'MicroSoft YaHei',
# 'weight' : 'bold',
# 'size' : 10}
# matplotlib.rc("font", **font)
# 通用字体设置
from matplotlib import font_manager
my_font = font_manager.FontProperties(fname="/Library/Fonts/Songti.ttc")
x = range(0,120)
y = [random.randint(20,35) for i in range(120)]
plt.figure(figsize=(20,8), dpi=80)
plt.plot(x,y)
x_label =list(x)
x_label_show = ["10点{}分".format(i) for i in range(60)]
x_label_show += ["11点{}分".format(i-60) for i in range(60,120)]
plt.xticks(x_label[::3],x_label_show[::3],rotation=45, fontproperties=my_font) # rotation旋转的度数
# 添加描述信息
plt.xlabel("时间",fontproperties=my_font)
plt.ylabel("温度 单位(°C)",fontproperties=my_font)
plt.title("10点到12点每分钟点气温变化情况",fontproperties=my_font)
plt.show()
效果展示: