美文网首页
Matplotlib: 在图中显示中文

Matplotlib: 在图中显示中文

作者: wzNote | 来源:发表于2020-03-07 17:05 被阅读0次

如果legend中包含中文,如果不做任何处理,中文将无法显示

import numpy as np
import matplotlib.pyplot as plt

y = np.array([2190.21, 3225.59, 4398.6, 4584.51, 4714.29, 4833.77, 3830.86, 3680, 4550, 5650])
x = np.arange(2009,2019)
 
fig, ax1 = plt.subplots() 
ax1.plot(x, y1, color='c', label='进口额')
plt.legend()

plt.show()

给legend设置中文字体

方法1:
from matplotlib.font_manager import FontProperties

font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc")
# 给legend设置字体
plt.legend(prop=font)

完整代码

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc")
y = np.array([2190.21, 3225.59, 4398.6, 4584.51, 4714.29, 4833.77, 3830.86, 3680, 4550, 5650])
x = np.arange(2009,2019)
 
fig, ax1 = plt.subplots() 
ax1.plot(x, y1, color='c', label='进口额')
plt.legend(prop=font)

plt.show()

效果


方法2:
from pylab import mpl

font = mpl.font_manager.FontProperties(fname=r"c:\windows\fonts\simsun.ttc")
plt.legend(prop=font)

给x和y轴标签设置字体

在上述基础上只需添加如下代码

plt.xlabel('年份',fontproperties = font)
plt.ylabel('亿元',fontproperties = font)

效果


image.png

给坐标轴上的字设置字体

x_val = ['2009年','2010年','2011年','2012年','2013年','2014年','2015年','2016年','2017年','2018年']
plt.xticks(x,x_val,fontproperties = font)   

效果:


完整代码

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
from pylab import mpl

font = mpl.font_manager.FontProperties(fname=r"c:\windows\fonts\simsun.ttc")
font1 = FontProperties(fname=r'c:\Windows\Fonts\simsun.ttc')
y = np.array([2190.21, 3225.59, 4398.6, 4584.51, 4714.29, 4833.77, 3830.86, 3680, 4550, 5650])
x = np.arange(2009,2019)
 
fig, ax1 = plt.subplots() 
ax1.plot(x, y1, color='c', label='进口额')
plt.legend(prop=font2)
plt.xlabel('年份',fontproperties = font)
plt.ylabel('亿元',fontproperties = font)
x_val = ['2009年','2010年','2011年','2012年','2013年','2014年','2015年','2016年','2017年','2018年']
plt.xticks(x,x_val,fontproperties = font)  ## 可以设置坐标字

plt.show()

更新

有个一劳永逸的方法

只要在开始加上以下几句话就可以了

import matplotlib as mpl
# 解决中文乱码问题
#sans-serif就是无衬线字体,是一种通用字体族。
#常见的无衬线字体有 Trebuchet MS, Tahoma, Verdana, Arial, Helvetica, 中文的幼圆、隶书等等。
mpl.rcParams['font.sans-serif']=['SimHei'] #指定默认字体 SimHei为黑体
mpl.rcParams['axes.unicode_minus']=False #用来正常显示负号 

相关文章

网友评论

      本文标题:Matplotlib: 在图中显示中文

      本文链接:https://www.haomeiwen.com/subject/mxvcdhtx.html