python matplotlib畫圖實例代碼分享
python的matplotlib包支持我們畫圖,有點非常多,現(xiàn)學習如下。
首先要導入包,在以后的示例中默認已經(jīng)導入這兩個包
import matplotlib.pyplot as plt import numpy as np
然后畫一個最基本的圖
t = np.arange(0.0, 2.0, 0.01)#x軸上的點,0到2之間以0.01為間隔
s = np.sin(2*np.pi*t)#y軸為正弦
plt.plot(t, s)#畫圖
plt.xlabel('time (s)')#x軸標簽
plt.ylabel('voltage (mV)')#y軸標簽
plt.title('About as simple as it gets, folks')#圖的標簽
plt.grid(True)#產(chǎn)生網(wǎng)格
plt.savefig("test.png")#保存圖像
plt.show()#顯示圖像
這是在一個窗口中畫單張圖的過程,那么如何畫多張圖呢?畫圖的過程相同,無非是畫多張,然后設定位置。
x1 = np.linspace(0.0, 5.0)#畫圖一
x2 = np.linspace(0.0, 2.0)#畫圖二
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)
plt.subplot(2, 1, 1)#面板設置成2行1列,并取第一個(順時針編號)
plt.plot(x1, y1, 'yo-')#畫圖,染色
plt.title('A tale of 2 subplots')
plt.ylabel('Damped oscillation')
plt.subplot(2, 1, 2)#面板設置成2行1列,并取第二個(順時針編號)
plt.plot(x2, y2, 'r.-')#畫圖,染色
plt.xlabel('time (s)')
plt.ylabel('Undamped')
plt.show()
兩張圖的示例如下


直方圖的畫法
# -*- coding:utf-8 -*-
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
mu = 100 # 正態(tài)分布的均值
sigma = 15 # 標準差
x = mu + sigma * np.random.randn(10000)#在均值周圍產(chǎn)生符合正態(tài)分布的x值
num_bins = 50
n, bins, patches = plt.hist(x, num_bins, normed=1, facecolor='green', alpha=0.5)
#直方圖函數(shù),x為x軸的值,normed=1表示為概率密度,即和為一,綠色方塊,色深參數(shù)0.5.返回n個概率,直方塊左邊線的x值,及各個方塊對象
y = mlab.normpdf(bins, mu, sigma)#畫一條逼近的曲線
plt.plot(bins, y, 'r--')
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')#中文標題 u'xxx'
plt.subplots_adjust(left=0.15)#左邊距
plt.show()
直方圖如下

3D圖像的畫法
3D離散點
#!/usr/bin/env python # encoding: utf-8 import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D x_list = [[3,3,2],[4,3,1],[1,2,3],[1,1,2],[2,1,2]] fig = plt.figure() ax = fig.gca(projection='3d') for x in x_list: ax.scatter(x[0],x[1],x[2],c='r') plt.show()
畫空間平面
from mpl_toolkits.mplot3d.axes3d import Axes3D from matplotlib import cm import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection='3d') X=np.arange(1,10,1) Y=np.arange(1,10,1) X, Y = np.meshgrid(X, Y) Z = 3*X+2*Y+30 surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1,cmap=cm.jet,linewidth=0, antialiased=True) ax.set_zlim3d(0,100) fig.colorbar(surf, shrink=0.5, aspect=5) plt.show()
畫空間曲面
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, 0.1)
Y = np.arange(-5, 5, 0.1)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)
#畫表面,x,y,z坐標, 橫向步長,縱向步長,顏色,線寬,是否漸變
ax.set_zlim(-1.01, 1.01)#坐標系的下邊界和上邊界
ax.zaxis.set_major_locator(LinearLocator(10))#設置Z軸標度
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))#Z軸精度
fig.colorbar(surf, shrink=0.5, aspect=5)#shrink顏色條伸縮比例(0-1),aspect顏色條寬度(反比例,數(shù)值越大寬度越窄)
plt.show()
3D圖分別如下



餅狀圖畫法
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'#設置標簽
sizes = [15, 30, 45, 10]#占比,和為100
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']#顏色
explode = (0, 0.1, 0, 0) #展開第二個扇形,即Hogs,間距為0.1
plt.pie(sizes, explode=explode, labels=labels, colors=colors,autopct='%1.1f%%', shadow=True, startangle=90)#startangle控制餅狀圖的旋轉方向
plt.axis('equal')#保證餅狀圖是正圓,否則會有一點角度偏斜
fig = plt.figure()
ax = fig.gca()
import numpy as np
ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors,autopct='%1.1f%%', shadow=True, startangle=90, radius=0.25, center=(0, 0), frame=True)
ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90, radius=0.25, center=(1, 1), frame=True)
ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90, radius=0.25, center=(0, 1), frame=True)
ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90,radius=0.25, center=(1, 0), frame=True)
ax.set_xticks([0, 1])#設置位置
ax.set_yticks([0, 1])
ax.set_xticklabels(["Sunny", "Cloudy"])#設置標簽
ax.set_yticklabels(["Dry", "Rainy"])
ax.set_xlim((-0.5, 1.5))
ax.set_ylim((-0.5, 1.5))
ax.set_aspect('equal')
plt.show()
餅狀圖如下:


平時用到的也就這幾種,掌握這幾種就差不多了,更多內(nèi)容見
https://matplotlib.org/users/screenshots.html
總結
以上就是本文關于python matplotlib畫圖實例代碼分享的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
相關文章
Python實現(xiàn)求兩個數(shù)組交集的方法示例
這篇文章主要介紹了Python實現(xiàn)求兩個數(shù)組交集的方法,涉及Python數(shù)組遍歷、排序、判斷、追加等相關操作技巧,需要的朋友可以參考下2019-02-02
Win8.1下安裝Python3.6提示0x80240017錯誤的解決方法
這篇文章主要為大家詳細介紹了Win8.1下安裝Python3.6提示0x80240017錯誤的解決方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-07-07
python數(shù)據(jù)預處理方式 :數(shù)據(jù)降維
今天小編就為大家分享一篇python數(shù)據(jù)預處理方式 :數(shù)據(jù)降維,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02

