matplotlib绘图时使用plt.xticks(fontproperties = my_font))设置刻度的中文,结果只有第一个可以正确显示,其他都只能按照默认的字体显示,请问有大佬知道如何解决吗?
from matplotlib import pyplot as plt
from matplotlib import font_manager
x = range(1,11)
x_1 = ['黑龙江','香港','台湾','上海','内蒙古','陕西','北京','山西','广东','澳门']
y = [1,2,3,4,5,6,7,8,9,10]
plt.figure(figsize=(20,8),dpi = 80)
#设置字体my_font
my_font = font_manager.FontProperties(fname='C:\Windows\Fonts\STHUPO.TTF',size=24)
#设置系统默认字体
plt.rcParams['font.sans-serif']=['SimHei']
plt.plot(x,y)
plt.xticks(range(len(x_1)),x_1,fontproperties = my_font)
y_ticks_label = ["{}加中文".format(i) for i in y]
plt.yticks(range(len(y)),y_ticks_label,fontproperties = my_font)
plt.title('为什么横纵坐标只有第一个刻度可以显示my_font设置的字体呢?',fontproperties = my_font)
plt.savefig('./t1.png')
plt.show()
希望能实现的是:
plt.xticks(range(len(x_1)),x_1,fontproperties = my_font)
y_ticks_label = ["{}加中文".format(i) for i in y]
plt.yticks(range(len(y)),y_ticks_label,fontproperties = my_font)
能将x轴和y轴的字体都按照my_font设置的显示出来!
新手刚入门Python,希望有大佬帮忙看看如何修改,非常感谢!
fontproperties = my_font中的fontproperties改为FontProperties
我也遇到了一样的问题。。不知道是什么原因
你好,我也遇到这个问题,可能是因为python的编译环境更换了,才出现这样的问题
是个bug,将/home/xxx/anaconda3/envs/yyy/lib/python3.8/site-packages/matplotlib/text.py 中的update()函数改为下面的即可:
def update(self, kwargs):
# docstring inherited
sentinel = object() # bbox can be None, so use another sentinel.
# Update fontproperties first, as it has lowest priority.
fontproperties = kwargs.get("fontproperties", sentinel) # 将原本的pop改为get
if fontproperties is not sentinel:
self.set_fontproperties(fontproperties)
# Update bbox last, as it depends on font properties.
bbox = kwargs.pop("bbox", sentinel)
super().update(kwargs)
if bbox is not sentinel:
self.set_bbox(bbox)
我用anaconda里jupyterlab也这样,换用pycharm就又可以了
太赞了,好用
#加上这句,可以解决设置刻度为中文时,不能显示的问题 plt.rcParams['font.sans-serif'] = ['SimHei']
from matplotlib import pyplot as plt
#加上这句,可以解决设置刻度为中文时,不能显示的问题
plt.rcParams['font.sans-serif'] = ['SimHei']