python學習之matplot

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.gridspec as gridspec
from matplotlib import animation

#Matplot的基本應用

x = np.linspace(-1,1,50)#定義x的數據範圍

y1 = 2*x + 1#定義y的數據範圍

y2 = x**2

plt.figure()#定義一個圖像窗口

plt.plot(x,y1)#plt花出曲線

plt.plot(x,y2)

plt.show()#顯示圖像

#4.1figure圖像

x = np.linspace(-3,3,50)#50爲生成的樣本數

y1 = 2*x+1

y2 = x**2

plt.figure(num=1,figsize=(8,5))#定義編號爲1 大小爲(8,5)

plt.plot(x,y1,color = 'red',linewidth= 2, linestyle = '--' )#定義顏色,線寬,先算形狀

plt.plot(x,y2,color = 'blue')

plt.show()

#4.2 設置座標軸

x = np.linspace(-3,3,50)#50爲生成的樣本數

y1 = 2*x+1

y2 = x**2

plt.figure(num=1,figsize=(8,5))#定義編號爲1 大小爲(8,5)

plt.plot(x,y1,color = 'red',linewidth= 2, linestyle = '--' )#定義顏色,線寬,先算形狀

plt.plot(x,y2,color = 'blue')

plt.xlim(-1,2)

plt.ylim(-2,3)

plt.xlabel('x')

plt.ylabel('y')

plt.show()

#自定義座標軸

x = np.linspace(-3,3,50)#50爲生成的樣本數

y1 = 2*x+1

y2 = x**2

plt.figure(num=1,figsize=(8,5))#定義編號爲1 大小爲(8,5)

plt.plot(x,y1,color = 'red',linewidth= 2, linestyle = '--' )#定義顏色,線寬,先算形狀

plt.plot(x,y2,color = 'blue')

plt.xlim(-1,2)

plt.ylim(-2,3)

plt.xlabel('x')

plt.ylabel('y')

new_ticks = np.linspace(-1,2,5)#小標從1到2分爲5個單位

print(new_ticks)

plt.xticks(new_ticks)#進行替換新下標

plt.yticks([-2,-1,1,2],[r'$reallybad$','$bad$','$well$','$reallywell$'])

plt.show()

#設置邊框屬性

x = np.linspace(-3,3,50)

y1 = 2*x+1

y2 = x**2

plt.figure(num=2,figsize=(8,5))

plt.plot(x,y1,color='red',linewidth = 2,linestyle = '--')

plt.plot(x,y2)

plt.xlim(-1,2)

plt.ylim(-2,3)

new_ticks = np.linspace(-1,2,5)#小標從-1到2分爲5各個單位

plt.xticks(new_ticks)

plt.yticks([-2,-1,1,2],[r'$1$','$2$','$3$','$4$'])

ax = plt.gca()#gca = get current axis

ax.spines['right'].set_color('none')#邊框屬性設置爲none 不顯示

ax.spines['top'].set_color('none')

plt.show()

#調整移動座標
#

x = np.linspace(-3,3,50)

y1 = 2*x+1

y2 = x**2

plt.figure(num=2,figsize=(8,5))

plt.plot(x,y1,color='red',linewidth = 2,linestyle = '--')

plt.plot(x,y2)

plt.xlim(-1,2)

plt.ylim(-2,3)

new_ticks = np.linspace(-1,2,5)#小標從-1到2分爲5各個單位

plt.xticks(new_ticks)

plt.yticks([-2,-1,1,2],[r'$1$','$2$','$3$','$4$'])

ax = plt.gca()#gca = get current axis

ax.spines['right'].set_color('none')#邊框屬性設置爲none 不顯示

ax.spines['top'].set_color('none')

ax.xaxis.set_ticks_position('bottom')#使用此函數設置x座標刻度數字或名稱的位置

ax.spines['bottom'].set_position(('data',0))

ax.yaxis.set_ticks_position('left')

ax.spines['left'].set_position(('data',0))#座標中心設置在(0,0)

plt.show()

#添加圖例
#

x = np.linspace(-3,3,50)

y1 = 2*x+1

y2 = x**2

plt.figure(num=2,figsize=(8,5))

plt.xlim(-1,2)

plt.ylim(-2,3)

new_ticks = np.linspace(-1,2,5)#小標從-1到2分爲5各個單位

plt.xticks(new_ticks)

plt.yticks([-2,-1,1,2],[r'$1$','$2$','$3$','$4$'])

l1 = plt.plot(x,y1,color = 'red',label = 'linear line')

l2 = plt.plot(x,y2,label = 'square line')

plt.legend(loc = 'best')

plt.show()

#添加標註

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

plt.scatter(x0,y0,s=1000,color='b')

plt.plot([x0,x0],[y0,0],'k--',lw = 2.5)#連接該兩點,k表示黑色,lw=2.5表示線粗細

plt.annotate(r'$2x0+1=%s$'%y0,xy=(x0,y0),xycoords ='data' ,xytext = (+30,-30),textcoords = 'offset points',fontsize = 16,arrowprops = dict(arrowstyle='->',connectionstyle = 'arc3,rad =.3'))

xycoords ='data' 是基於數據的值來選擇位置;xytext = (+30,-30)和textcoord = 'offset points'對於標註位置描述和xy偏差值,arrowprops對於圖中間頭類型設置

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

-3.7,3設置文字位置;fontdict設置文字的字體

plt.show()

#4,5 能見度調整

x = np.linspace(-3,3,50)

y = 0.1*x

plt.figure()

plt.plot(x,y,linewidth = 10,zorder = 1)

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

label.set_fontsize(12)重新調整字體大小 bbox設置目的內容的透明度相關參數 edgecolor設置邊框

alpha設置透明度 zoeder設置圖層順序

#

for label in ax.get_xticklabels() + ax.get_yticklabels():

label.set_fontsize(12)

label.set_bbox(dict(facecolor='red',edgecolor = 'None',alpha = 0.7,zorder=2))

#

plt.show()

#5.畫圖種類
#5.1Scatter散點圖

n = 1024

x = np.random.normal(0,1,n)#每一個點的x值

y = np.random.normal(0,1,n)#每一個點的y值

T = np.arctan2(y,x)#返回給定的xy值的反正切值

plt.scatter(x,y,s =75,c=T,alpha= 0.5)#size爲75,顏色爲T,透明度爲50%,利用xticks函數來隱藏座標軸

plt.xlim(-1.5,1.5)

plt.xticks(())#忽略xticks

plt.ylim(-1.5,1.5)

plt.ylim(-1.5,1.5)

plt.show()

#numpy.random.normal(loc=0.0, scale=1.0, size=None)
#loc均值 scale方差 size 輸出值的個數

#條形圖
#基本圖形

n = 12

x = np.arange(n)

y1 = (1-x/float(n))*np.random.uniform(0.5,1,n)#均勻分佈

y2 = (1-x/float(n))*np.random.uniform(0.5,1,n)

plt.bar(x,+y1,facecolor = '#9999ff',edgecolor = 'white')

plt.bar(x,-y2,facecolor = '#ff9999',edgecolor = 'white')

#

標記值

for x,y in zip(x,y1): #打包兩個元組的值

plt.text(x+0.2,y+0.2,'%.2f'%y,ha = 'center',va='bottom')

ha表示橫向對其,bottom表示向下對其

x = np.arange(n)#好舒服啊

for x,y in zip(x,y2):

plt.text(x+0.2,-y-0.2,'%.2f'%y,ha='center',va='top')

#

plt.xlim(-0.5,n)

plt.ylim(-1.25,1.25)

plt.show()

#5.3等高線圖

n = 256

x = np.linspace(-3,3,n)

y = np.linspace(-3,3,n)

x,y = np.meshgrid(x,y)#座標向量返回座標矩陣

def f(x,y):

return (1 - x / 2 + x 5 + y3)*np.exp(-x2 - y 2)

plt.contourf(x,y,f(x,y),8,alpha = 0.75,cmap = plt.cm.hot)

8標示等高線成分 alpha表示透明度 cmap表示color map

使用contour函數進行等高線繪製 參數依次爲x,y,f(x,y),顏色選擇黑色,線條寬度爲0.5

c = plt.contour(x,y,f(x,y),8,colors = 'black',linewidth = 0.5)

plt.clabel添加等高值 inline控制是否將label畫在線裏,字體大小爲10

plt.clabel(c,inline = True,fontsize = 10)

plt.show()

#5.4 Image圖片

a = np.array(np.linspace(0,1,9)).reshape(3,3)

print(a)

plt.imshow(a,interpolation = 'nearest',cmap = 'bone',origin = 'lower')

origin代表選擇原點位置

plt.colorbar(shrink = .92) #shrink將圖片長度變爲原來的92%

plt.show()

#5.5 3D圖像

fig = plt.figure()#定義圖像窗口

ax = Axes3D(fig)#在窗口上添加3D座標

將xy值編織成柵格

x = np.arange(-4,4,0.25)

y = np.arange(-4,4,0.25)

#
#

x,y = np.meshgrid(x,y)

#

r = np.sqrt(x2+y2)

z = np.sin(r)#高度值

將colormap rain bow填充顏色,之後將三維圖像投影到xy平面做等高線圖,其中rstride和cstride表示row和column的寬度

ax.plot_surface(x,y,z,rstride=1,cstride=1,cmap=plt.get_cmap('rainbow'))

添加xy平面等高線 投影到z平面

ax.contourf(x,y,z,zdir='z',offset=-2,cmap = plt.get_cmap('rainbow'))#把圖像進行投影的圖形 offset表示比0底兩個位置

ax.set_zlim(-2,2)

plt.show()

#多圖合併顯示
#6.1 Subplot多合一顯示
#6.1 subplot多合一顯示
#均勻圖中圖

plt.figure()

plt.subplot(2,2,1)#表示整個圖像分割成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(2,2,4)

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

plt.show()

不均勻圖中圖

plt.figure()

plt.subplot(2,1,1)#表示整個圖像分割成2行兩列,當前位置爲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(2,3,6)

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

plt.show()

#6.2 subplot分格顯示

plt.figure()

使用plt.subplot2grid創建第一個小圖,(3,3)表示將整個圖像分割成3行3列,(0,0)表示從第0行0列開始作圖

colspan表示列的跨度爲3.colspan和rowspan缺省時默認跨度爲1

ax1 = plt.subplot2grid((3,3),(0,0),colspan=3)

ax1.plot([1,2],[1,2])

ax1.set_title('ax1_title')

將圖像分割成3行3列,從第一行0列開始做圖,列的跨度爲2

ax2 = plt.subplot2grid((3,3),(1,0),colspan=2)

ax3 = plt.subplot2grid((3,3),(1,2),rowspan=2)

ax4 = plt.subplot2grid((3,3),(2,0))

ax4.scatter([1,2],[2,2])

ax4.set_xlabel('ax4_x')

ax4.set_ylabel('ax4_y')

ax5 = plt.subplot2grid((3,3),(2,1))

plt.show()

plt.figure()

gs = gridspec.GridSpec(3,3)

ax6 = plt.subplot(gs[0,:])#gs[0:1]表示佔第0行和所有列

ax7 = plt.subplot(gs[1,:2])#第一行和之前的所有

ax10 = plt.subplot(gs[1:,2])

ax8 = plt.subplot(gs[-1,0])

ax9 = plt.subplot(gs[-1,-2])

plt.show()

#圖中圖

fig = plt.figure()

創建數據

x = [1,2,3,4,5,6,7]

y = [1,3,4,2,5,8,6]

繪製大圖:假設大圖的1大小爲10,那麼大圖包含在由(1,1)開始,寬8高8的座標系中

left,bottom,width,height = 0.1,0.1,0.8,0.8

ax1 = fig.add_axes([left,bottom,width,height]) #main axes

ax1.plot(x,y,'r')#繪製大圖,顏色爲red

ax1.set_xlabel('x')

ax1.set_ylabel('y')

ax1.set_title('title')

繪製小圖,注意座標系位置和大小的改變

ax2 = fig.add_axes([0.2,0.6,0.25,0.25])

ax2.plot(x,y,'b')#顏色爲blue

ax2.set_xlabel('x')

ax2.set_ylabel('y')

ax2.set_title('= = = = = ')

#

ax3 = fig.add_axes([0.6,0.2,0.25,0.25])

ax3.plot(x,y,'g')#顏色爲blue

ax3.set_xlabel('x')

ax3.set_ylabel('y')

ax3.set_title('++++++++')

#6.4次座標軸

x = np.arange(0,10,0.1)

y1 = 0.5*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()

#7動畫

fig,ax = plt.subplots()
x = np.arange(0,2*np.pi,0.01)
line = ax.plot(x,np.sin(x))
#構造自定義動畫函數animate,用來更新每一幀上x和y的座標值,參數表示第i針
def animate(i):
line.set_ydata(np.sin(x+i/100))
return line
#構造開始幀init函數
def init():
line.set_ydata(np.sin(x))
return line

ani = animation.FuncAnimation(fig=fig,func = animate,frames=200,init_func=init,interval = 20 ,blit = False)
plt.show()

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