matplotlib的用法

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 #顯示負號
    也可以用上面屏蔽的代碼來指定字體


下面是效果
宋體
宋體
黑體
黑體

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章