matplotlib的用法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011529752/article/details/72751393

matplotlib的用法

详见注释

#-*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import matplotlib as mpl
import  numpy as np
import numpy.random as rd
from matplotlib.font_manager import FontProperties
#导入字体
# font = FontProperties(fname='//usr/share/fonts/truetype/arphic/ukai.ttc',size=12,weight=1)
#
# plt.rcParams['axes.unicode_minus']=False #显示负号


# 生成数据
n1=20
n2=15
X1=np.array(range(0,n1,1))
X2=np.array(range(0,2*n2,2))
Y1=np.array(rd.randn(n1))
Y2=np.array(rd.rand(n2))
print(X1)
print(X2)
print(Y1)
print(Y2)

#划分子区域
plt.figure()
axe1=plt.subplot(2,2,1)#子区域对象
axe2=plt.subplot(2,2,2)
axe3=plt.subplot(2,1,2)
#划线
lines1=axe1.plot(X1,Y1,'r-')
lines2=axe2.plot(X2,Y2,'g-')
lines3=axe3.plot(X1,Y1,'r-')
lines3.append(axe3.plot(X2,Y2,'g-')[0])

#装饰
#调整坐标范围
axe1.axis([0,30,-1,1])#前面是x轴的范围,后面是y轴的范围
axe2.axis([0,30,0,1])
axe3.axis([0,30,-1,1])

#插入图例
# axe1.set_xlabel('X_值',fontproperties = font)
# axe1.set_ylabel(u"Y_值",fontproperties = font)
# axe2.set_xlabel(u"X_值",fontproperties = font)
# axe2.set_ylabel(u"Y_值",fontproperties = font)
# axe3.set_xlabel(u"X_值",fontproperties = font)
# axe3.set_ylabel(u"Y_值",fontproperties = font)
axe1.set_xlabel('X_值')
axe1.set_ylabel(u"Y_值")
axe2.set_xlabel(u"X_值")
axe2.set_ylabel(u"Y_值")
axe3.set_xlabel(u"X_值")
axe3.set_ylabel(u"Y_值")

lines1[0].set_label(u"line1线")
lines2[0].set_label("line2")
list(map(lambda i:lines3[i].set_label("line"+'%d'%(i+1)),[0,1]))
# lines3[0].set_label("line1")
# lines3[1].set_label("line2")
axe1.legend()#显示图例
axe2.legend()#
axe3.legend()#
plt.show()#显示figure

注意子区域和画出的线都是对象
结果如下图

关于中文显示的问题
1. 字体一定要在系统中安装
2. matplotlibrc 文件中
font.family : monospace
font.monospace : 想要的字体,xxxxxxxx
前的#号一定要去掉,本机的路径是/home/wdh/anaconda3/envs/python3.4/lib/python3.4/site-packages/matplotlib/mpl-data/fonts/matplotlibrc
3. 网上说的font.family : sans-serifs,不知为何就是不行,总是提示UserWarning: findfont: Font family [‘sans-serifs’] not found. Falling back to Bitstream Vera Sans
(prop.get_family(), self.defaultFamily[fontext])),而改用第2点的就可以

  1. 在前3点的前提下,可以通过语句
    mpl.rcParams[‘font.monospace’] = [‘simsun’] #指定默认字体
    plt.rcParams[‘axes.unicode_minus’]=False #显示负号
    也可以用上面屏蔽的代码来指定字体


下面是效果
宋体
宋体
黑体
黑体

猜你喜欢

转载自blog.csdn.net/u011529752/article/details/72751393