使用matplotlib畫簡單的圖形:
#-*- coding:utf-8 -*- from numpy.random import randn import matplotlib.pyplot as plt fig=plt.figure() ax1=fig.add_subplot(2,2,1) plt.plot(randn(50).cumsum(),'k--') ax2=fig.add_subplot(2,2,2) #bins越大矩形越窄 alpha表示顏色深度 ax2.hist(randn(10000), bins = 30, color = 'red', alpha = 1) ax3=fig.add_subplot(2,2,3) plt.plot([1.5, 2, 4, -2, 1.6]) plt.show()
運行結果:

散點圖
#-*- coding:utf-8 -*- from pylab import * import matplotlib.pyplot as plt mpl.rcParams['font.sans-serif'] = ['SimHei'] n = 1024 X = np.random.normal(0,1,n) Y = np.random.normal(0,1,n) for i in range(1,10): scatter(i, i) plt.title(u"散點圖",color='red') show()

pyplot.subplots有幾個選項
nrows:subplot的行數
ncols:subplot的列數
sharex:所有subplot共享x軸刻度
sharey:所有subplot共享Y軸刻度
#-*- coding:utf-8 -*- from numpy.random import randn from matplotlib import pyplot as plt fig,axes=plt.subplots(2,2,sharex=True,sharey=True) for i in range(2): for j in range(2): axes[i,j].hist(randn(50),bins=50,color='red',alpha=1) plt.show()

矩陣圖
#-*- coding:utf-8 -*- from pylab import * #使用中文 mpl.rcParams['font.sans-serif'] = ['SimHei'] #顯示負號 matplotlib.rcParams['axes.unicode_minus'] = False n=32 list1=[i for i in range(1,33)] list2=[i for i in range(-32,0)] n= np.arange(n) xlim(-1,32) ylim(-35,35) xlabel(u'每個城市招聘人數') bar(n, list1, facecolor='yellow', edgecolor='white') bar(n, list2, facecolor='red', edgecolor='white') for x,y in zip(n,list1): text(x, y, '%d' % y, ha='center', va= 'bottom' ) for x,y in zip(n,list2): text(x, y-3, '%d' % y, ha='center', va= 'bottom') show()

餅圖
# -*- 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') # 保證餅狀圖是正圓,否則會有一點角度偏斜 plt.show()

# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' # 設置標簽 colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral'] # 顏色 explode = (0.1, 0.2, 0, 0) # 展開第二個扇形,即Hogs,間距為0.1 fig = plt.figure() ax = fig.gca() 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()

熱力圖
#-*- coding:utf-8 -*- from pylab import * def f(x,y): 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) X,Y = np.meshgrid(x,y) contourf(X, Y, f(X,Y), 8, alpha=.75, cmap='jet') C = contour(X, Y, f(X,Y), 8, colors='black', linewidth=.5) show()

利用numpy來實現sin函數
#-*- coding:utf-8 -*- from pylab import * #使用中文 mpl.rcParams['font.sans-serif'] = ['SimHei'] #顯示負號 matplotlib.rcParams['axes.unicode_minus'] = False t=np.arange(0.0,2.0,0.01)#0到2之間,以0.01為間距 s=np.sin(2*np.pi*t)#利用numpy實現2sinπx plt.plot(t,s) plt.xlabel('t的值') plt.ylabel('s的值') #這里同時可以使用plt.xlim()和plt.ylim()來限制x、y軸的范圍 plt.show()

#-*- coding:utf-8 -*- from pylab import * #使用中文 mpl.rcParams['font.sans-serif'] = ['SimHei'] #顯示負號 matplotlib.rcParams['axes.unicode_minus'] = False 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) plt.plot(x1,y1,'y*-')#y表示顏色,*表示點的樣子,-表示連接 plt.title('圖1') plt.subplot(2,1,2)#最后一個2表示在第二個位置 plt.plot(x1,y2,'r.--') plt.title('圖2') plt.show()

#-*- coding:utf-8 -*- from pylab import * #使用中文 mpl.rcParams['font.sans-serif'] = ['SimHei'] #顯示負號 matplotlib.rcParams['axes.unicode_minus'] = False mu=1000 sigma=15 x=mu+sigma*np.random.randn(10000)#在均值周圍產生符合正態分布x值 num_bins=50 n,bins,patches=plt.hist(x,num_bins,normed=1,facecolor='green',alpha=0.5) #直方圖函數,x為x軸的值,normed=1表示為概率密度,即和為一,綠色方塊,色深參數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$') plt.subplots_adjust(left=0.15) plt.show()

# -*- coding:utf-8 -*- from pylab import * 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 = Axes3D(fig) for x in x_list: ax.scatter(x[0], x[1], x[2], c='r') plt.show()

from pylab import * from mpl_toolkits.mplot3d import Axes3D 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()

# -*- coding:utf-8 -*-
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顏色條寬度(反比例,數值越大寬度越窄)
plt.show()

