Matplotlib有以下重要對(duì)象:
figure (畫布)榆综,ax (坐標(biāo)系)榕吼,axis (坐標(biāo)軸)
后面的例子會(huì)用到這些對(duì)象薄料。
文章目錄
數(shù)學(xué)公式編輯可參考官方文檔:
mathtext
如果因?yàn)閰?shù)缺少說明或代碼注釋不到位導(dǎo)致理解困難的話非常抱歉~推薦一個(gè)視頻教程狂丝,有很多筆記源于上面的教程(2016年的)救斑,有不清楚的地方也可以去上面的教程看一看~
子圖subplot
面向?qū)ο笫骄幊?/p>
import numpy as np
from matplotlib import pyplot as plt
'''
ax1=fig.add_subplot(221)
參數(shù):
第一個(gè)參數(shù)是fig對(duì)象每行擁有的子圖總數(shù)
第二個(gè)參數(shù)是fig對(duì)象每列擁有的子圖總數(shù)
第三個(gè)參數(shù)是子圖的位置
返回值:返回Axes實(shí)例
'''
x=np.arange(1,100)
fig=plt.figure()
axl=fig.add_subplot(221)
axl.plot(x,x)
ax2=fig.add_subplot(222)
ax2.plot(x,-x)
ax3=fig.add_subplot(223)
ax3.plot(x,x**2)
ax4=fig.add_subplot(224)
ax4.plot(x,np.log(x))
plt.show()
交互式編程
import numpy as np
from matplotlib import pyplot as plt
X=np.arange(1,100)
plt.subplot(221)
plt.plot(X,X)
plt.subplot(222)
plt.plot(X,-X)
plt.subplot(223)
plt.plot(X,X*X)
plt.subplot(224)
plt.plot(X,np.log(X))
交互式編程意思是可以輸入命令即使得到反饋童本,可以看到效果,和命令行類似脸候,如下圖穷娱,輸入plt.grid(True)便可以給當(dāng)前子圖設(shè)置網(wǎng)格
01
生成多個(gè)figure
import numpy as np
from matplotlib import pyplot as plt
fig1=plt.figure()
ax1=fig1.add_subplot(111)
ax1.plot([1,2,3],[3,2,1])
fig2=plt.figure()
ax2=fig2.add_subplot(111)
ax2.plot([1,2,3],[1,2,3])
plt.show()
網(wǎng)格
import numpy as np
from matplotlib import pyplot as plt
X=np.arange(0,10,1)
fig=plt.figure()
ax=fig.add_subplot(111)
plt.plot(X,X*2)
ax.grid(color='r',linestyle='-.',linewidth='2') #設(shè)置網(wǎng)格屬性
plt.show()
圖例
Matplotlib.legend()設(shè)置圖例,有兩個(gè)常用的參數(shù)运沦,loc是圖例在圖像中的位置泵额,ncol為顯示圖例的列數(shù),比如MatPlotlib.legend(loc=4,ncol=3)
loc | Value |
---|---|
0 | 智能位置 |
1 | 右上角 |
2 | 左上角 |
3 | 左下角 |
4 | 右下角 |
import numpy as np
from matplotlib import pyplot as plt
X=np.arange(1,100)
plt.plot(X,X*2,label='Normal')
plt.plot(X,X*3,label='Fast')
plt.plot(X,X*4,label='Faster')
plt.legend(loc=1,ncol=3)
plt.show()
#面向?qū)ο蟮姆绞剑?import numpy as np
from matplotlib import pyplot as plt
X=np.arange(1,100)
fig=plt.figure()
ax=fig.add_subplot(111)
l=plt.plot(X,X,label='label')
ax.legend()
#ax.legend(['ax legend'])
plt.show()
坐標(biāo)軸范圍
用plt.axis()調(diào)整坐標(biāo)軸范圍携添,參數(shù)是一個(gè)列表嫁盲,比如plt.axis([-10,10,0,100])表示-10
x
10, 0
y
100
也可以用plt.xlim()和plt.ylim()分別調(diào)整x軸和y軸范圍,指定參數(shù)時(shí)烈掠,比如plt.xlim(xmin=6)羞秤,則只調(diào)整x軸左邊缸托。
import numpy as np
from matplotlib import pyplot as plt
X=np.arange(-10,11,1)
fig=plt.figure()
ax=fig.add_subplot(111)
l=plt.plot(X,X*X)
plt.axis([-6,6,10,60])
#plt.xlim(-6,6)
#plt.xlim(xmin=-6)
plt.show()
坐標(biāo)軸刻度
import numpy as np
from matplotlib import pyplot as plt
x=np.arange(-10,11,1)
plt.plot(x,x)
ax=plt.gca() #獲取當(dāng)前圖像的坐標(biāo)軸
ax.locator_params(nbins=10) #(版本不同,效果有細(xì)微差別)把坐標(biāo)軸8等份瘾蛋,因?yàn)樽鴺?biāo)軸兩邊-10,10還有空白俐镐,加起來就10份了
#也可以指定某個(gè)軸,比如:ax.locator_params('x',nbins=10)
plt.show()
顯示日期
import numpy as np
from matplotlib import pyplot as plt
import datetime
import matplotlib as mpl
fig=plt.figure()
#設(shè)置日期序列
start=datetime.datetime(2018,9,30)
stop=datetime.datetime(2019,9,30)
delta=datetime.timedelta(days=1)
dates=mpl.dates.drange(start,stop,delta)
y=np.random.rand(len(dates))
ax=plt.gca()
ax.plot_date(dates,y,linestyle='-',marker='')
#設(shè)置日期顯示格式(x軸顯示格式)
date_format=mpl.dates.DateFormatter('%Y-%m-%d')
ax.xaxis.set_major_formatter(date_format)
#使x軸顯示的日期自適應(yīng)窗口大小
fig.autofmt_xdate()
plt.show()
添加坐標(biāo)軸
雙y軸
import numpy as np
from matplotlib import pyplot as plt
x=np.arange(2,20,1)
y1=x*x
y2=np.log(x)
fig=plt.figure()
ax1=fig.add_subplot(111)
ax1.plot(x,y1)
ax1.set_ylabel('Y1')
ax2=ax1.twinx() #ax2和ax1共x軸
ax2.plot(x,y2,'r')
ax2.set_ylabel('Y2')
ax1.set_xlabel('Compare Y1 and Y2')
plt.show()
添加注釋
import numpy as np
from matplotlib import pyplot as plt
x=np.arange(-10,11,1)
y=x*x
plt.plot(x,y)
'''
參數(shù):
xy為箭頭頭部的坐標(biāo)
xytext為箭頭尾部(文字)的坐標(biāo)
arrowprops指定箭頭的屬性
其中facecolot是箭頭顏色哺哼,frac是箭頭占整個(gè)箭頭符號(hào)的比例
headwidth為箭頭頭部的寬度京革,width為鍵身的寬度
'''
plt.annotate('this is the bottom',xy=(0,4),xytext=(0,30),
arrowprops=dict(facecolor='g',frac=0.2,headwidth=30,width=18))
plt.show()
添加文字
import numpy as np
from matplotlib import pyplot as plt
x=np.arange(-10,11,1)
y=x*x
plt.plot(x,y)
'''
plt.text()參數(shù):
前面兩個(gè)數(shù)字是要顯示文字的起始坐標(biāo)
'y=x*x'是要顯示的文字
family可以設(shè)置字體,
常用字體包括:‘serif’, ‘sans-serif’, ‘cursive’, ‘fantasy’, or ‘monospace’
style設(shè)置風(fēng)格幸斥,比如斜體
weight設(shè)置字體粗細(xì)(這個(gè)參數(shù)可以是數(shù)字0~1000,也可以是文字:ultralight,light,normal,regular,book,medium,roman,semibold,demibold,demi,bold,heavy,extra bold,black)
bbox設(shè)置一個(gè)矩形框包住要顯示的文字咬扇,其中alpha是透明度
'''
plt.text(-1,40,'y=x*x',family='fantasy',size=20,color='r',style='italic',weight='demi',
bbox=dict(facecolor='r',alpha=0.2))
plt.show()
顯示數(shù)學(xué)公式
公式參考:mathtext
import numpy as np
from matplotlib import pyplot as plt
fig=plt.figure()
ax=fig.add_subplot(111)
ax.set_xlim([1,7])
ax.set_ylim([1,5])
#數(shù)學(xué)公式書寫要用$$包括
ax.text(2,3,r'$\sin(0)=\cos(\frac{\pi}{2})$',size=30)
plt.show()
區(qū)域填充
填充與x軸圍成的區(qū)域
import numpy as np
from matplotlib import pyplot as plt
x=np.linspace(0,5*np.pi,1000)
y1=np.sin(x)
y2=np.sin(2*x)
# plt.plot(x,y1)
# plt.plot(x,y2)
# alpha是透明度甲葬,'b'是藍(lán)色,'r'是紅色
plt.fill(x,y1,'b',alpha=0.3)
plt.fill(x,y2,'r',alpha=0.3)
plt.show()
填充兩條線之間的區(qū)域
import numpy as np
from matplotlib import pyplot as plt
x=np.linspace(0,5*np.pi,1000)
y1=np.sin(x)
y2=np.sin(2*x)
# plt.plot(x,y1)
# plt.plot(x,y2)
fig=plt.figure()
ax=plt.gca()
ax.plot(x,y1,color='r')
ax.plot(x,y2,color='black')
#因?yàn)閤取值是離散的懈贺,所以當(dāng)x間距較大時(shí)经窖,可能會(huì)出現(xiàn)空白區(qū)域,參數(shù) interpolate設(shè)為True的意義就是讓這些空白區(qū)域也可以顯色
ax.fill_between(x,y1,y2,where=y1>y2,facecolor='yellow',interpolate=True)
ax.fill_between(x,y1,y2,where=y2>y1,facecolor='r',interpolate=True)
plt.show()
生成形狀
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.patches as mpatches
'''
fig, ax = plt.subplots()等價(jià)于fig, ax = plt.subplots(ncols=1, nrows=1)
等價(jià)于
fig=plt.figure()
ax=ax = fig.add_subplot(111)
'''
fig,ax=plt.subplots()
'''
使用array()函數(shù)可以將列表轉(zhuǎn)化為數(shù)組
'''
xy1=[0.2,0.2]
#xy1=np.array([0.2,0.2])
xy2=np.array([0.2,0.8])
xy3=np.array([0.8,0.2])
xy4=np.array([0.8,0.8])
circle=mpatches.Circle(xy1,0.05)
ax.add_patch(circle)
rect=mpatches.Rectangle(xy2,0.2,0.1,color='r')
ax.add_patch(rect)
ellipse=mpatches.Ellipse(xy4,0.4,0.2,color='y')
ax.add_patch(ellipse)
# 第二個(gè)參數(shù)設(shè)為5表示邊數(shù)為5梭灿,0.1表示圖形中心到頂點(diǎn)的距離(類比圓的半徑)
polygon=mpatches.RegularPolygon(xy3,5,0.1,color='g')
ax.add_patch(polygon)
#設(shè)置橫縱坐標(biāo)比例相等画侣,否則會(huì)顯示橢圓
plt.axis('equal')
#添加網(wǎng)格
plt.grid()
plt.show()
樣式美化
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import patches as mpatches
'''
# print(plt.style.available) #樣式
返回:
['bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn-bright',
'seaborn-colorblind', 'seaborn-dark-palette', 'seaborn-dark', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted',
'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks',
'seaborn-white', 'seaborn-whitegrid', 'seaborn', 'Solarize_Light2', 'tableau-colorblind10', '_classic_test']
'''
#設(shè)置樣式:
plt.style.use('dark_background')
fig,axes=plt.subplots(ncols=2 , nrows=2)
ax1, ax2, ax3, ax4 = axes.ravel()
x, y = np.random.normal(size=(2,100))
ax1.plot(x,y,'o')
x=np.arange(0,10)
y=np.arange(0,10)
# # plt.rcParams['axes.color_cycle'] 為默認(rèn)的顏色循環(huán)
# ncolors=len(plt.rcParams['axes.color_cycle'])
#獲取顏色循環(huán)
colors = [color['color'] for color in list(plt.rcParams['axes.prop_cycle'])]
shift=np.linspace(0,10,7)
for s in shift:
ax2.plot(x,y+s,'-')
x=np.arange(5)
y1,y2,y3=np.random.randint(1,25,size=(3,5))
width=0.25
ax3.bar(x,y1,width)
ax3.bar(x+width,y2,width,color=colors[1])
ax3.bar(x+2*width,y2,width,color=colors[2])
for color in colors:
xy=np.random.normal(size=2)
ax4.add_patch(plt.Circle(xy,radius=0.3,color=color))
ax4.axis('equal')
ax4.grid()
plt.show()
極坐標(biāo)
import numpy as np
from matplotlib import pyplot as plt
r=np.arange(1,6,1)
theta=[np.pi*i/2 for i in range(5)]
#設(shè)置極坐標(biāo)系
ax=plt.subplot(111,projection='polar')
ax.plot(theta,r,color='r',linewidth=3)
ax.grid(True)
plt.show()
'''
2019-10-15更新
'''
坐標(biāo)軸標(biāo)注
我們有時(shí)需要標(biāo)注x軸是什么,y軸是什么堡妒,還需要給x,y軸設(shè)置標(biāo)簽配乱,比如下面的例子:
import numpy as np
from matplotlib import pyplot as plt
def func(x):
return -(x-3)*(x-7)+9
x=np.linspace(0,10)
y=func(x)
fig,ax=plt.subplots()
plt.plot(x,y,'r',linewidth=2)
a=2
b=8
ax.set_xticks([a,b]) # 設(shè)置x標(biāo)簽
ax.set_yticks([]) # 設(shè)置y標(biāo)簽(這里為空)
ax.set_xticklabels(['$x_1$','$x_2$']) #設(shè)置x標(biāo)簽的顯示形式
plt.figtext(0.9,0.05,'$x$') #前面兩個(gè)參數(shù)的范圍在0,1之間,是相對(duì)窗口的位置皮迟,而不是坐標(biāo)軸的位置搬泥,可以看后面生成的圖
plt.figtext(0.1,0.9,'$y$')
plt.show()