Python--matplotlib.pyplot繪圖系列

一、註釋:

只做代碼的搬運工。註釋很纖細,適合收藏自學。想了解更多可在B站搜《莫煩Python》

二、目錄:

 1. 繪製出直線和二次曲線
 2. 優化座標軸
 3. 設置x,y常態座標
 4. 爲曲線和直線添加圖標說明
 5. 給圖像中特殊點進行註釋
 6. 座標被線條遮住時,設置透明度使其顯現。
 7. 散點圖
 8. 條形直方圖
 9. 山地高低勢能圖
 10. 色塊與漸變條形圖註釋
 11. 3D圖像與平面映射
 12. 畫板分塊顯示(方法一)
 13. 畫板分塊顯示(方法一)多舉例
 14. 畫板分塊顯示(方法二、更普遍)
 15. 大圖嵌套小圖
 16. 倆條線公用x軸,顯示在一張fig上
 17. 導入animation(活躍)繪製動圖***

三、正文:
1.

###繪製出直線和二次曲線
import matplotlib.pyplot as plt
import numpy as np
#在指定的間隔內[start,stop]返回num個均勻間隔的數字。
x=np.linspace(-3,3,50)
y1=2*x+1
y2=x**2
'''
plt.figure(
    num=None,      //圖像編號或名稱,數字爲編號 ,字符串爲名稱  
                   //第一個默認爲1,然後依次1,2,3;在IDLE運行上可以看出,這裏無法顯示。
    figsize=None,  //設置整個畫板大小
    dpi=None,      //指定繪圖對象的分辨率,即每英寸多少個像素,缺省值爲80;1英寸等於2.5cm 
    facecolor=None,//背景顏色
    edgecolor=None,//邊框顏色
    frameon=True,  //是否顯示邊框
    FigureClass=<class 'matplotlib.figure.Figure'>,
    clear=False,
    **kwargs,
)
'''
plt.figure(facecolor='y',dpi=100,num='csd')
plt.plot(x,y1)
#一個figure只能畫一張
plt.figure(figsize=(8,5),facecolor='y')
plt.plot(x,y2)
plt.plot(x,y1,color='red',linestyle='--',linewidth=1.0)
plt.show()

在這裏插入圖片描述
在這裏插入圖片描述

2.

#####改變畫板視圖的顯示位置(相當於放大突出顯示)
#####優化座標軸,然他用途更廣
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(-3,3,50)
y1=2*x+1
y2=x**2

plt.figure(facecolor='y')
plt.plot(x,y2)
plt.plot(x,y1,color='red',linestyle='--',linewidth=1.0)

#顯示圖大小(座標)的取值範圍,
plt.xlim((-1,2))
plt.ylim((-2,3))

#加入x,y標籤或說明
plt.xlabel('I am x')
plt.ylabel('I am y')

#在plt.xlim((-1,2))指定的x軸顯示範圍內均分5個座標點
new_ticks=np.linspace(-1,2,5)
print(new_ticks)
plt.xticks(new_ticks)

#plt.yticks([-2,-1,1,2,3],['really bad','bad','normal','good','really good'])
#正則表達式顯示好看字體,打印空格時用到 '/'轉譯符,</+空格>
'''
#plt.yticks([],[],)  
前倆個參數爲數組,
第二個代表標籤(可以非數字)會覆蓋第一個默認數字標籤,
第三個參數對最後標籤起修飾作用(比如,形狀、顏色)

'''
plt.yticks([-2,-1,1,2,3],[r'$really\ bad\ \alpha$',r'$bad$',r'$normal$',r'$good$',r'$really\ good$'],rotation=30)

plt.show()

在這裏插入圖片描述
3.

#####設置x,y常態座標(return 我們畫圖做數學題的常見座標系)

import matplotlib.pyplot as plt
import numpy as np

x=np.linspace(-3,3,50)
y1=2*x+1
y2=x**2

plt.figure()
plt.plot(x,y2)
plt.plot(x,y1,color='red',linestyle='--',linewidth=1.0)

#顯示圖大小(座標)的取值範圍,
plt.xlim((-1,2))
plt.ylim((-2,3))


plt.xlabel('I am x')
plt.ylabel('I am y')


new_ticks=np.linspace(-1,2,5)
print(new_ticks)
plt.xticks(new_ticks)
#plt.yticks([-2,-1,1,2,3],['really bad','bad','normal','good','really good'])
#正則表達式顯示好看字體
plt.yticks([-2,-1,1,2,3],[r'$really\ bad\ \alpha$',r'$bad$',r'$normal$',r'$good$',r'$really\ good$'])


#gca='get current axis'  axis:軸
ax=plt.gca()
#設置右邊、上邊的軸線爲透明,隱藏     spines:脊椎
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
#將ax獲取的'bottom'軸設爲x軸
#將ay獲取的'bottom'軸設爲y軸
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
#設x,y的起點爲:(0,0)原點
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))


plt.show()

在這裏插入圖片描述
4.

#####爲曲線和直線添加圖標說明

import matplotlib.pyplot as plt
import numpy as np

x=np.linspace(-3,3,50)
y1=2*x+1
y2=x**2

plt.figure(figsize=(7,7))
l1,=plt.plot(x,y2,)
l2,=plt.plot(x,y1,color='red',linestyle='--',linewidth=1.0,)
#legend:圖標說明   
#loc參數:定義圖標說明顯示位置默認爲'best',可選參數有:'upper center', 'lower center', 'center left', 'center right' etc.、
#handles:可根據labels大小自動設置邊框大小。
plt.legend(handles=[l1,l2,],labels=['aaa','bbb',],loc='upper center')


#顯示圖大小(座標)的取值範圍,
plt.xlim((-1,2))
plt.ylim((-2,3))


plt.xlabel('I am x')
plt.ylabel('I am y')


new_ticks=np.linspace(-1,2,5)
print(new_ticks)
plt.xticks(new_ticks)
#plt.yticks([-2,-1,1,2,3],['really bad','bad','normal','good','really good'])
#正則表達式顯示好看字體
plt.yticks([-2,-1,1,2,3],[r'$really\ bad\ \alpha$',r'$bad$',r'$normal$',r'$good$',r'$really\ good$'])


#gca='get current axis'  axis:軸
ax=plt.gca()
#設置右邊的軸線爲透明,隱藏     spines:脊椎
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))

plt.show()

在這裏插入圖片描述
5.

#########給圖像中特殊點進行註釋
#########在畫板中相對圖像添加自定義文本


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')
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))


x0=1
y0=2*x0+1
#設置一個分散點,S:點的大小。
plt.scatter(x0,y0,s=50,color='b')
#在倆端點之間,畫一條黑色寬度爲2的虛線。
plt.plot([x0,x0],[y0,0],'k--',lw=2)


#method 1
####################
#annotate:中文意思:註釋   
# %y:相當於C語言中的取地址符&,爲%s賦值。
#xytest:設置文本(2x+1=3)相對於註釋點的相對位置。    
#textcoords='offset points':默認值,偏執點(根據xytext設置值偏離(x0,y0)),最後以此爲錨點來畫註釋曲線指向(x0,y0)
#arrowprops:設置style,    ,箭頭、角度、半徑
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'))


#method2
'''
plt.text(x,y,s,fontdict,)
x, y : 放置文本的位置

s : str  the 文本內容.

fontdict : 用於覆蓋默認文本屬性的字典(自定義文本樣式)

'''
plt.text(-3.7,5,r'$This\ is\ the\ some\ text.\ \mu\ \sigma_i\ \alpha_t$',fontdict={'size':16,'color':'r'})


plt.show()

在這裏插入圖片描述
6.

#######當有時候,座標被線條遮住時,設置透明度使其顯現。

import matplotlib.pyplot as plt
import numpy as np

x=np.linspace(-3,3,50)
y=0.1*x

plt.figure()
#alpha:不透明度
plt.plot(x,y,linewidth=10,color='green',alpha=0.5)
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))

#取出x,y軸的標籤(座標),設置大小爲12,爲標籤加box_style
for label in ax.get_xticklabels()+ ax.get_yticklabels():
    label.set_fontsize(12)
    label.set_bbox(dict(facecolor='red',edgecolor='None',alpha=0.7))

plt.show()





在這裏插入圖片描述
7.

#####散點圖

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 value

'''
np.arange()
一個參數時,參數值爲終點,起點取默認值0,步長取默認值1。
兩個參數時,第一個參數爲起點,第二個參數爲終點,步長取默認值1。
三個參數時,第一個參數爲起點,第二個參數爲終點,第三個參數爲步長。其中步長支持小數
'''
#plt.scatter(X,Y,s=75,c=T,alpha=0.5)
#plt.scatter設置散點圖。
plt.scatter(np.arange(5),np.arange(5))

#plt.xlim((-1.5,1.5))
#plt.ylim((-1.5,1.5))

#不傳參,去掉外圍座標
plt.xticks(())
plt.yticks(())

plt.show()

在這裏插入圖片描述
8.

#####條形直方圖

import matplotlib.pyplot as plt
import numpy as np

n=12
X=np.arange(12)
# 1/float(2)=0.5
#np.random.uniform:從一個均勻分佈[low,high)中隨機採樣,注意定義域是左閉右開,即包含low,不包含high,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)

#bar:條、棒。代表柱狀圖
plt.bar(X,+Y1,facecolor='red',edgecolor='white')
plt.bar(X,-Y2,facecolor='blue',edgecolor='white')

#zip:x,y以元組爲單位,依次在X,Y數組中取值。
for x,y in zip(X,Y1):
    #ha:horizontal alignment
    plt.text(x+0.4,y+0.05,'%.2f'% y,ha='center',va='bottom')

for x,y in zip(X,Y2):
    #ha:horizontal alignment
    plt.text(x+0.4,-y-0.05,'%.2f'% y,ha='center',va='top')
    
plt.xticks(())
plt.yticks(())



plt.show()


在這裏插入圖片描述
9.

######山地高低勢能圖
'''
np.linspace(x,y,n):以n爲總數均勻劃分
np.arange(x,y,n)  :以n爲步長均勻劃分
'''

import matplotlib.pyplot as plt
import numpy as np

def f(x,y):
    b=(1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
    #the height function
    return b

n=256
x=np.linspace(-3,3,n)
y=np.linspace(-3,3,n)
#meshgrid:網格
'''
np.meshgrid(x,y)基於向量x和向量y中包含的座標返回二維網格座標。

x是向量[1 2 3],y是向量[1 2 3 4 5];
矩陣X的每一行都是x,即[1 2 3],總共有length(y)=5行;
矩陣Y的每一列都是y,即[1 2 3 4 5],總共有length(x)=3列。

X =                                         Y = 

    1 2 3                                   1    1    1

    1 2 3                              2    2    2

    1 2 3                              3    3    3

    1 2 3                              4    4    4

    1 2 3                              5    5    5
'''
X,Y=np.meshgrid(x,y)

#contour:等位線

#use plt.contourf to filling contours
#X,Y and value for(X,Y)point
#8:8個劃分
#cmap=color_map        contourf:填色等位面
plt.contourf(X,Y,f(X,Y),8,alpha=0.75,cmap=plt.cm.hot)

#use plt.contour to add contour lines    contour:定位線 
C=plt.contour(X,Y,f(X,Y),8,colors='black',linewidths=0.5)

#adding label   
#inline:在線裏面添加label
plt.clabel(C,inline=True,fontsize=10)

plt.xticks(())
plt.yticks(())

plt.show()


在這裏插入圖片描述
10.

#######色塊與漸變條形圖註釋
import matplotlib.pyplot as plt
import numpy as np

#image data
#以數字指定顏色,傳入數組,後reshape(3,3)重塑3——3矩陣
a=np.array([0.313660827978,0.365348418405,0.423733120134,
           0.365348418405,0.439599930621,0.525083754405,
           0.423733120134,0.525083754405,0.651536351379]).reshape(3,3)

plt.figure(figsize=(8,5),facecolor='white')
"""
fornthe value of"interpolation",check this:
http://matplotlib.org/examples/images_contours_and_fields/interpolation_methods.html

"""
#cmap:color map;
# cmap='bone':設置圖片的顏色爲骨白色。
#origin相對於原始3X3矩陣的首尾部起始顯示,   origin='upper'   
#interpolation='nearest'
plt.imshow(a,cmap='bone',origin='lower')
#shrink:定義註釋bar相對於色塊的收縮比
plt.colorbar(shrink=0.9)

plt.xticks(())
plt.yticks(())
plt.show(

在這裏插入圖片描述
11.

########3D圖像與平面映射
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
fig=plt.figure(facecolor='white')
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)
#height value
Z=np.cos(R)

#r,cstride:黑線的密度   rstride:橫軸間距;cstride:縱軸間距
#rainbow:彩虹色
ax.plot_surface(X,Y,Z,rstride=1,cstride=1,edgecolor='black',cmap=plt.get_cmap('rainbow'))

#zdir->z;沿縱軸方向壓等高線,映射到地面
ax.contourf(X,Y,Z,zdir='z',offset=-2,cmap='rainbow')
ax.set_zlim(-2,2)
plt.show()

在這裏插入圖片描述
12.

########畫板分塊顯示(方法一)
import matplotlib.pyplot as plt
import numpy as np
plt.figure(facecolor='white')

#把很多張圖畫到一個顯示界面,把面板切分成一個一個子圖
#subplot前面倆參數指定的是一個畫板被分割成的行和列,後面一個參數則指的是當前正在繪製的編號!
plt.subplot(2,2,1)
plt.plot([0,1],[0,1])

plt.subplot(2,2,2)
plt.plot([0,1],[0,2])

plt.subplot(2,2,3)
plt.plot([0,1],[0,3])

plt.subplot(224)
plt.plot([0,1],[0,4])

plt.show()

在這裏插入圖片描述
13.

########畫板分塊顯示(方法一)多舉例
import matplotlib.pyplot as plt
import numpy as np
plt.figure(facecolor='white')
plt.subplot(2,1,1)
plt.plot([0,1],[0,1])

plt.subplot(2,3,4)
plt.plot([0,1],[0,2])

plt.subplot(2,3,5)
plt.plot([0,1],[0,3])

plt.subplot(236)
plt.plot([0,1],[0,4])

plt.show()

在這裏插入圖片描述
14.

#######畫板分塊顯示(方法二、更普遍)

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

#method 1:subplot2grid
############################
plt.figure(facecolor='white')
ax1=plt.subplot2grid((3,3),(0,0),colspan=3,rowspan=1)
ax1.plot([1,2],[1,2])
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)

在這裏插入圖片描述
15.

######大圖嵌套小圖

'''
調用plt.figure.add_axes 重定義座標系佔用整個fig的百分比及位置,從而實現功能。
left,bottom,width,height=0.1,0.1,0.8,0.8:重定義座標系邊框位置
'''

import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt

fig=plt.figure(facecolor='white')
x=[1,2,3,4,5,6,7]
y=[1,3,4,2,5,8,6]

#佔整個figure()的百分比
left,bottom,width,height=0.1,0.1,0.8,0.8
ax1=fig.add_axes([left,bottom,width,height])
ax1.plot(x,y,'r')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('title')

left,bottom,width,height=0.2,0.6,0.25,0.25
ax1=fig.add_axes([left,bottom,width,height])
ax1.plot(x,y,'b')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('title_inside 1')

plt.axes([0.6,.2,.25,.25])
plt.plot(y[::-1],x,'g')
plt.xlabel('x')
plt.ylabel('y')
plt.title('title_inside 2')
plt.show()

在這裏插入圖片描述
16.

#####倆條線公用x軸,顯示在一張fig上

import matplotlib.pyplot as plt
import numpy as np

plt.figure(facecolor='white')

x=np.arange(0,10,0.1)
y1=0.05*x**2
y2=-1*y1

fig,ax1=plt.subplots(facecolor='y')
#座標反轉
ax2=ax1.twinx()
ax1.plot(x,y1,'g-')
ax2.plot(x,y2,'b--')

ax1.set_xlabel('X_data')
ax1.set_ylabel('Y1',color='g')
ax2.set_ylabel('Y2',color='r')

plt.show()

在這裏插入圖片描述
17.

#######導入animation(活躍)繪製動圖

import numpy as np
import matplotlib.pyplot as plt#導入動畫模塊
from matplotlib import animation

fig,ax=plt.subplots(facecolor='y')

x=np.arange(0,2*np.pi,0.01)
line,=ax.plot(x,np.sin(x))

def anime(i):
    line.set_ydata(np.sin(x+i/100))
    return line,
def init():
    line.set_ydata(np.sin(x))
    return line,

#frames:多窗口頁面,幀數
#interval:間隔 20ms
#blit:位塊傳送
ani=animation.FuncAnimation(fig=fig,func=anime,frames=100,init_func=init,interval=20,blit=False)

plt.show()

在這裏插入圖片描述

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