python中matplotlib画图_Python-matplotlib画图(莫烦笔记)
這個是我對于莫煩老師的matplotlib模塊的視頻做的一個筆記。
1.前言
Matplotlib是一個python的 2D繪圖庫,它以各種硬拷貝格式和跨平臺的交互式環(huán)境生成出版質(zhì)量級別的圖形。通過Matplotlib,開發(fā)者可以僅需要幾行代碼,便可以生成繪圖,直方圖,功率譜,條形圖,錯誤圖,散點圖等。
2.簡單的使用
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1,1,50)#從(-1,1)均勻取50個點
y = 2 * x
plt.plot(x,y)
plt.show()y = 2x圖像注意:
1.如果不使用plo.show()圖表是顯示不出來的,因為可能你要對圖表進(jìn)行多種的描述,所以通過顯式的調(diào)用show()可以避免不必要的錯誤。
3.Figure對象
我這里單拿出一個一個的對象,然后后面在進(jìn)行總結(jié)。在matplotlib中,整個圖表為一個figure對象。其實對于每一個彈出的小窗口就是一個Figure對象,那么如何在一個代碼中創(chuàng)建多個Figure對象,也就是多個小窗口呢?
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1,1,50)
y1 = x ** 2
y2 = x * 2
#這個是第一個figure對象,下面的內(nèi)容都會在第一個figure中顯示
plt.figure()
plt.plot(x,y1)
#這里第二個figure對象
plt.figure(num = 3,figsize = (10,5))
plt.plot(x,y2)
plt.show()
這里需要注意的是:我們看上面的每個圖像的窗口,可以看出figure并沒有從1開始然后到2,這是因為我們在創(chuàng)建第二個figure對象的時候,指定了一個num = 3的參數(shù),所以第二個窗口標(biāo)題上顯示的figure3。
對于每一個窗口,我們也可以對他們分別去指定窗口的大小。也就是figsize參數(shù)。
若我們想讓他們的線有所區(qū)別,我們可以用下面語句進(jìn)行修改
plt.plot(x,y2,color = 'red',linewidth = 3.0,linestyle = '--')
4.設(shè)置坐標(biāo)軸
我們想更改在圖表上顯示x,y的取值范圍:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1,1,50)
y = x *2
plt.plot(x,y)
plt.show()默認(rèn)的橫縱坐標(biāo)
#在plt.show()之前添加
plt.xlim((0,2))
plt.ylim((-2,2))更改橫縱坐標(biāo)的取值范圍之后
給橫縱坐標(biāo)設(shè)置名稱:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1,1,50)
y = x * 2
plt.xlabel("x'slabel")#x軸上的名字
plt.ylabel("y's;abel")#y軸上的名字
plt.plot(x,y,color='green',linewidth = 3)
plt.show()
把坐標(biāo)軸換成不同的單位:
new_ticks = np.linspace(-1,2,5)
plt.xticks(new_ticks)
#在對應(yīng)坐標(biāo)處更換名稱
plt.yticks([-2,-1,0,1,2],['really bad','b','c','d','good'])更換后的坐標(biāo)名稱
那么如果我想把坐標(biāo)軸上的字體更改成數(shù)學(xué)的那種形式:
#在對應(yīng)坐標(biāo)處更換名稱
plt.yticks([-2,-1,0,1,2],[r'$really\ bad$',r'$b$',r'$c\ \alpha$','d','good'])將單位改成數(shù)學(xué)的字體格式
注意:我們?nèi)绻褂每崭竦脑捫枰M(jìn)行對空格的轉(zhuǎn)義"\ "這種轉(zhuǎn)義才能輸出空格;
我們可以在里面加一些數(shù)學(xué)的公式,如"\alpha"來表示
。
如何去更換坐標(biāo)原點,坐標(biāo)軸呢?我們在plt.show()之前:
#gca = 'get current axis'
#獲取當(dāng)前的這四個軸
ax = plt.gca()
#設(shè)置脊梁(也就是包圍在圖標(biāo)四周的默認(rèn)黑線)
#所以設(shè)置脊梁的時候,一共有四個方位
ax.spines['right'].set_color('r')
ax.spines['top'].set_color('none')
#將底部脊梁作為x軸
ax.xaxis.set_ticks_position('bottom')
#ACCEPTS:['top' | 'bottom' | 'both'|'default'|'none']
#設(shè)置x軸的位置(設(shè)置底的時候依據(jù)的是y軸)
ax.spines['bottom'].set_position(('data',0))
#the 1st is in 'outward' |'axes' | 'data'
#axes : precentage of y axis
#data : depend on y data
ax.yaxis.set_ticks_position('left')
# #ACCEPTS:['top' | 'bottom' | 'both'|'default'|'none']
#設(shè)置左脊梁(y軸)依據(jù)的是x軸的0位置
ax.spines['left'].set_position(('data',0))更改坐標(biāo)軸位置
5.legend圖例
我們很多時候會再一個figures中去添加多條線,那我們?nèi)绾稳^(qū)分多條線呢?這里就用到了legend。
#簡單的使用
l1, = plt.plot(x, y1, label='linear line')
l2, = plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--', label='square line')
#簡單的設(shè)置legend(設(shè)置位置)
#位置在右上角
plt.legend(loc = 'upper right')
l1, = plt.plot(x, y1, label='linear line')
l2, = plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--', label='square line')
plt.legend(handles = [l1,l2],labels = ['up','down'],loc = 'best')
#the ',' is very important in here l1, = plt...and l2, = plt...for this step
"""legend( handles=(line1, line2, line3),labels=('label1', 'label2', 'label3'),'upper right')shadow = True 設(shè)置圖例是否有陰影The *loc* location codes are::'best' : 0,'upper right' : 1,'upper left' : 2,'lower left' : 3,'lower right' : 4,'right' : 5,'center left' : 6,'center right' : 7,'lower center' : 8,'upper center' : 9,'center' : 10,"""
這里需要注意的是:如果我們沒有在legend方法的參數(shù)中設(shè)置labels,那么就會使用畫線的時候,也就是plot方法中的指定的label參數(shù)所指定的名稱,當(dāng)然如果都沒有的話就會拋出異常;
其實我們plt.plot的時候返回的是一個線的對象,如果我們想在handle中使用這個對象,就必須在返回的名字的后面加一個","號;
legend = plt.legend(handles = [l1,l2],labels = ['hu','tang'],loc = 'upper center',shadow = True)
frame = legend.get_frame()
frame.set_facecolor('r')#或者0.9...更改后的圖例樣式
6.在圖片上加一些標(biāo)注annotation
在圖片上加注解有兩種方式:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3,3,50)
y = 2*x + 1
plt.figure(num = 1,figsize =(8,5))
plt.plot(x,y)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
#將底下的作為x軸
ax.xaxis.set_ticks_position('bottom')
#并且data,以y軸的數(shù)據(jù)為基本
ax.spines['bottom'].set_position(('data',0))
#將左邊的作為y軸
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
print("-----方式一-----")
x0 = 1
y0 = 2*x0 + 1
plt.plot([x0,x0],[0,y0],'k--',linewidth = 2.5)
plt.scatter([x0],[y0],s = 50,color='b')
plt.annotate(r'$2x+1 =%s$'% y0,xy = (x0,y0),xycoords = 'data',
xytext=(+30,-30),textcoords = 'offset points',fontsize = 16
,arrowprops = dict(arrowstyle='->',
connectionstyle="arc3,rad=.2"))
plt.show()第一種annotation
plt.annotate(r'$2x+1 =%s$'% y0,xy = (x0,y0),xycoords = 'data',
xytext=(+30,-30),textcoords = 'offset points',fontsize = 16
,arrowprops = dict(arrowstyle='->',
connectionstyle="arc3,rad=.2"))
注意:xy就是需要進(jìn)行注釋的點的橫縱坐標(biāo);
xycoords = 'data'說明的是要注釋點的xy的坐標(biāo)是以橫縱坐標(biāo)軸為基準(zhǔn)的;
xytext=(+30,-30)和textcoords='data'說明了這里的文字是基于標(biāo)注的點的x坐標(biāo)的偏移+30以及標(biāo)注點y坐標(biāo)-30位置,就是我們要進(jìn)行注釋文字的位置;
fontsize = 16就說明字體的大小;
arrowprops = dict()這個是對于這個箭頭的描述,arrowstyle='->'這個是箭頭的類型,connectionstyle="arc3,rad=.2"這兩個是描述我們的箭頭的弧度以及角度的。
print("-----方式二-----")
plt.text(-3.7,3,r'$this\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',
fontdict={'size':16,'color':'r'})第二種標(biāo)注方式
這里先介紹一下plot中的一個參數(shù):
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3,3,50)
y1 = 0.1*x
y2 = x**2
plt.figure()
#zorder控制繪圖順序
plt.plot(x,y1,linewidth = 10,zorder = 2,label = r'$y_1\ =\ 0.1*x$')
plt.plot(x,y2,linewidth = 10,zorder = 1,label = r'$y_2\ =\ x^{2}$')
plt.legend(loc = 'lower right')
plt.show()
如果改成:
#zorder控制繪圖順序
plt.plot(x,y1,linewidth = 10,zorder = 1,label = r'$y_1\ =\ 0.1*x$')
plt.plot(x,y2,linewidth = 10,zorder = 2,label = r'$y_2\ =\ x^{2}$')
下面我們看一下這個圖:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3,3,50)
y1 = 0.1*x
y2 = x**2
plt.figure()
#zorder控制繪圖順序
plt.plot(x,y1,linewidth = 10,zorder = 1,label = r'$y_1\ =\ 0.1*x$')
plt.plot(x,y2,linewidth = 10,zorder = 2,label = r'$y_2\ =\ x^{2}$')
plt.ylim(-2,2)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
plt.show()執(zhí)行效果
從上面看,我們可以看見我們軸上的坐標(biāo)被掩蓋住了,那么我們怎么去修改他呢?
print(ax.get_xticklabels())
print(ax.get_yticklabels())
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(12)
label.set_bbox(dict(facecolor = 'white',edgecolor='none',alpha = 0.8,zorder = 2))
讓坐標(biāo)軸顯示出來
這里需要注意:ax.get_xticklabels()獲取得到就是坐標(biāo)軸上的數(shù)字;
set_bbox()這個bbox就是那坐標(biāo)軸上的數(shù)字的那一小塊區(qū)域,從結(jié)果我們可以很明顯的看出來;
facecolor = 'white',edgecolor='none,第一個參數(shù)表示的這個box的前面的背景,邊上的顏色。
7.畫圖的種類
1.scatter散點圖
import matplotlib.pyplot as plt
import numpy as np
n = 1024
X = np.random.normal(0,1,n)
Y = np.random.normal(0,1,n)
T = np.arctan2(Y,X)#for color later on
plt.scatter(X,Y,s = 75,c = T,alpha = .5)
plt.xlim((-1.5,1.5))
plt.xticks([])#ignore xticks
plt.ylim((-1.5,1.5))
plt.yticks([])#ignore yticks
plt.show()散點圖
2.柱狀圖
import matplotlib.pyplot as plt
import numpy as np
n = 12
X = np.arange(n)
Y1 = (1 - X/float(n)) * np.random.uniform(0.5,1.0,n)
Y2 = (1 - X/float(n)) * np.random.uniform(0.5,1.0,n)
#facecolor:表面的顏色;edgecolor:邊框的顏色
plt.bar(X,+Y1,facecolor = '#9999ff',edgecolor = 'white')
plt.bar(X,-Y2,facecolor = '#ff9999',edgecolor = 'white')
#描繪text在圖表上
# plt.text(0 + 0.4, 0 + 0.05,"huhu")
for x,y in zip(X,Y1):
#ha : horizontal alignment
#va : vertical alignment
plt.text(x + 0.01,y+0.05,'%.2f'%y,ha = 'center',va='bottom')
for x,y in zip(X,Y2):
# ha : horizontal alignment
# va : vertical alignment
plt.text(x+0.01,-y-0.05,'%.2f'%(-y),ha='center',va='top')
plt.xlim(-.5,n)
plt.yticks([])
plt.ylim(-1.25,1.25)
plt.yticks([])
plt.show()柱狀圖
3.Contours等高線圖
import matplotlib.pyplot as plt
import numpy as np
def f(x,y):
#the height function
return (1-x/2 + x**5+y**3) * np.exp(-x **2 -y**2)
n = 256
x = np.linspace(-3,3,n)
y = np.linspace(-3,3,n)
#meshgrid函數(shù)用兩個坐標(biāo)軸上的點在平面上畫網(wǎng)格。
X,Y = np.meshgrid(x,y)
#use plt.contourf to filling contours
#X Y and value for (X,Y) point
#這里的8就是說明等高線分成多少個部分,如果是0則分成2半
#則8是分成10半
#cmap找對應(yīng)的顏色,如果高=0就找0對應(yīng)的顏色值,
plt.contourf(X,Y,f(X,Y),8,alpha = .75,cmap = plt.cm.hot)
#use plt.contour to add contour lines
C = plt.contour(X,Y,f(X,Y),8,colors = 'black',linewidth = .5)
#adding label
plt.clabel(C,inline = True,fontsize = 10)
#ignore ticks
plt.xticks([])
plt.yticks([])
plt.show()等高線
4.image圖片
import matplotlib.pyplot as plt
import numpy as np
#image data
a = np.array([0.313660827978, 0.365348418405, 0.423733120134,
0.365348418405, 0.439599930621, 0.525083754405,
0.423733120134, 0.525083754405, 0.651536351379]).reshape(3,3)
'''for the value of "interpolation",check this:http://matplotlib.org/examples/images_contours_and_fields/interpolation_methods.htmlfor the value of "origin"= ['upper', 'lower'], check this:http://matplotlib.org/examples/pylab_examples/image_origin.html'''
#顯示圖像
#這里的cmap='bone'等價于plt.cm.bone
plt.imshow(a,interpolation = 'nearest',cmap = 'bone' ,origin = 'up')
#顯示右邊的欄
plt.colorbar(shrink = .92)
#ignore ticks
plt.xticks([])
plt.yticks([])
plt.show()顯示圖片
5.3D數(shù)據(jù)
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
#X Y value
X = np.arange(-4,4,0.25)
Y = np.arange(-4,4,0.25)
X,Y = np.meshgrid(X,Y)
R = np.sqrt(X**2 + Y**2)
#hight value
Z = np.sin(R)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
"""============= ================================================Argument Description============= ================================================*X*, *Y*, *Z* Data values as 2D arrays*rstride* Array row stride (step size), defaults to 10*cstride* Array column stride (step size), defaults to 10*color* Color of the surface patches*cmap* A colormap for the surface patches.*facecolors* Face colors for the individual patches*norm* An instance of Normalize to map values to colors*vmin* Minimum value to map*vmax* Maximum value to map*shade* Whether to shade the facecolors============= ================================================"""
# I think this is different from plt12_contours
ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=plt.get_cmap('rainbow'))
"""========== ================================================Argument Description========== ================================================*X*, *Y*, Data values as numpy.arrays*Z**zdir* The direction to use: x, y or z (default)*offset* If specified plot a projection of the filled contouron this position in plane normal to zdir========== ================================================"""
ax.set_zlim(-2, 2)
plt.show()
8.多圖合并展示
1.使用subplot函數(shù)
import matplotlib.pyplot as plt
plt.figure(figsize = (6,5))
ax1 = plt.subplot(3,1,1)
ax1.set_title("ax1 title")
plt.plot([0,1],[0,1])
#這種情況下如果再數(shù)的話以334為標(biāo)準(zhǔn)了,
#把上面的第一行看成是3個列
ax2 = plt.subplot(334)
ax2.set_title("ax2 title")
ax3 = plt.subplot(335)
ax4 = plt.subplot(336)
ax5 = plt.subplot(325)
ax6 = plt.subplot(326)
plt.show()案例一
import matplotlib.pyplot as plt
plt.figure(figsize = (6,4))
#plt.subplot(n_rows,n_cols,plot_num)
plt.subplot(211)
# figure splits into 2 rows, 1 col, plot to the 1st sub-fig
plt.plot([0, 1], [0, 1])
plt.subplot(234)
# figure splits into 2 rows, 3 col, plot to the 4th sub-fig
plt.plot([0, 1], [0, 2])
plt.subplot(235)
# figure splits into 2 rows, 3 col, plot to the 5th sub-fig
plt.plot([0, 1], [0, 3])
plt.subplot(236)
# figure splits into 2 rows, 3 col, plot to the 6th sub-fig
plt.plot([0, 1], [0, 4])
plt.tight_layout()
plt.show()案例二
2.分格顯示
#method 1: subplot2grid
import matplotlib.pyplot as plt
plt.figure()
#第一個參數(shù)shape也就是我們網(wǎng)格的形狀
#第二個參數(shù)loc,位置,這里需要注意位置是從0開始索引的
#第三個參數(shù)colspan跨多少列,默認(rèn)是1
#第四個參數(shù)rowspan跨多少行,默認(rèn)是1
ax1 = plt.subplot2grid((3,3),(0,0),colspan = 3,rowspan = 1)
#如果為他設(shè)置一些屬性的話,如plt.title,則用ax1的話
#ax1.set_title(),同理可設(shè)置其他屬性
ax1.set_title("ax1_title")
ax2 = plt.subplot2grid((3,3),(1,0),colspan = 2,rowspan = 1)
ax3 = plt.subplot2grid((3,3),(1,2),colspan = 1,rowspan = 2)
ax4 = plt.subplot2grid((3,3),(2,0),colspan = 1,rowspan = 1)
ax5 = plt.subplot2grid((3,3),(2,1),colspan = 1,rowspan = 1)
plt.show()method1 result
#method 2:gridspec
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
plt.figure()
gs = gridspec.GridSpec(3,3)
#use index from 0
ax1 = plt.subplot(gs[0,:])
ax1.set_title("ax1 title")
ax2 = plt.subplot(gs[1,:2])
ax2.plot([1,2],[3,4],'r')
ax3 = plt.subplot(gs[1:,2:])
ax4 = plt.subplot(gs[-1,0])
ax5 = plt.subplot(gs[-1,-2])
plt.show()method2 result
#method 3 :easy to define structure
#這種方式不能生成指定跨行列的那種
import matplotlib.pyplot as plt
#(ax11,ax12),(ax13,ax14)代表了兩行
#f就是figure對象,
#sharex:是否共享x軸
#sharey:是否共享y軸
f,((ax11,ax12),(ax13,ax14)) = plt.subplots(2,2,sharex = True,sharey = True)
ax11.set_title("a11 title")
ax12.scatter([1,2],[1,2])
plt.show()method3 result
3.圖中圖
import matplotlib.pyplot as plt
fig = plt.figure()
x = [1,2,3,4,5,6,7]
y = [1,3,4,2,5,8,6]
#below are all percentage
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
#使用plt.figure()顯示的是一個空的figure
#如果使用fig.add_axes會添加軸
ax1 = fig.add_axes([left, bottom, width, height])# main axes
ax1.plot(x,y,'r')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('title')
ax2 = fig.add_axes([0.2, 0.6, 0.25, 0.25]) # inside axes
ax2.plot(y, x, 'b')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('title inside 1')
# different method to add axes
####################################
plt.axes([0.6, 0.2, 0.25, 0.25])
plt.plot(y[::-1], x, 'g')
plt.xlabel('x')
plt.ylabel('y')
plt.title('title inside 2')
plt.show()畫中畫
4.次坐標(biāo)軸
# 使用twinx是添加y軸的坐標(biāo)軸
# 使用twiny是添加x軸的坐標(biāo)軸
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0,10,0.1)
y1 = 0.05 * x ** 2
y2 = -1 * y1
fig,ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x,y1,'g-')
ax2.plot(x,y2,'b-')
ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data',color = 'g')
ax2.set_ylabel('Y2 data',color = 'b')
plt.show()次坐標(biāo)
9.animation動畫
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
fig,ax = plt.subplots()
x = np.arange(0,2*np.pi,0.01)
#因為這里返回的是一個列表,但是我們只想要第一個值
#所以這里需要加,號
line, = ax.plot(x,np.sin(x))
def animate(i):
line.set_ydata(np.sin(x + i/10.0))#updata the data
return line,
def init():
line.set_ydata(np.sin(x))
return line,
# call the animator. blit=True means only re-draw the parts that have changed.
# blit=True dose not work on Mac, set blit=False
# interval= update frequency
#frames幀數(shù)
ani = animation.FuncAnimation(fig=fig, func=animate, frames=100, init_func=init,
interval=20, blit=False)
plt.show()animation
總結(jié)
以上是生活随笔為你收集整理的python中matplotlib画图_Python-matplotlib画图(莫烦笔记)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python requests 1004
- 下一篇: python我想对你说_python学习