Matplotlib是 Python 2D-繪圖領域使用最普遍的套件,能夠簡易地將數據圖形化,而且提供多樣化的輸出格式。
matplotlib有兩個接口,一個是狀態機層的接口,經過pyplot模塊來進行管理;一個是面向對象的接口,經過pylab模塊將全部的功能函數所有導入其單獨的命名空間內。dom
使用conda安裝以下:conda install matplotlib
ide
Matplotlib基本圖表結構包括座標軸(X軸、Y軸)、座標軸標籤(axisLabel)、
座標軸刻度(tick)、座標軸刻度標籤(tick label)、繪圖區(axes)、畫布(figure)。
函數
Figure表明一個繪製面板,其中能夠包涵多個Axes(即多個圖表)。
Axes表示一個圖表 ,一個Axes包涵:titlek、xaxis、yaxis。
爲了支持pylab中的gca()等函數,Figure對象內部保存有當前軸的信息,所以不建議直接對Figure.axes屬性進行列表操做,而應該使用add_subplot, add_axes, delaxes等方法進行添加和刪除操做。spa
# -*- coding=utf-8 -*- import matplotlib.pyplot as plt import numpy as np if __name__ == "__main__": fig = plt.figure() ax1 = fig.add_axes([0.1, 0.45, 0.8, 0.5]) ax2 = fig.add_axes([0.1, 0.1, 0.8, 0.2]) x1 = np.linspace(0.0, 5.0) x2 = np.linspace(0.0, 3.0) y1 = np.cos(2 * np.pi * x1) * np.exp(-x1) y2 = np.cos(2 * np.pi * x2) ax1.patch.set_facecolor("green") ax1.grid(True) line1 = ax1.plot(x1, y1, 'yo-') line2 = ax2.plot(x2, y2, 'r.-') plt.show()
網格線設置plt.grid(color='r',linestyle='-.')
axis:座標軸,可選值爲x,y
color:支持十六進制顏色
linestyle: –,-.,:
alpha:透明度,0——13d
座標軸範圍設置plt.axis([xmin,xmax,ymin,ymax])
也能夠經過xlim(xmin,xmax),ylim(xmin,xmax)方法設置座標軸範圍code
# -*- coding=utf-8 -*- import matplotlib.pyplot as plt import numpy as np if __name__ == "__main__": x = np.arange(-10, 10, 0.1) y = x ** 2 plt.plot(x, y,) plt.axis([-10, 10, 0, 100]) plt.show()
關閉座標軸plt.axis('off')
orm
設置畫布比例plt.figure(figsize=(a,b))
a是x軸刻度比例,b是y軸刻度比例。對象
圖例設置有兩種方法,一種是分別在plot函數中使用label參數指定,再調用plt.legend()方法顯示圖例;一種是直接在legend方法中傳入字符串列表設置圖例。blog
# -*- coding=utf-8 -*- import matplotlib.pyplot as plt import numpy as np if __name__ == "__main__": x = np.arange(-10, 10, 0.1) y = x ** 2 plt.plot(x, y, label='y = x ** 2') plt.legend() plt.show()
使用legend函數設置圖例時,參數以下:
圖例名稱列表:傳遞的圖例名稱列表必須與曲線繪製順序一致。
loc:用於設置圖例標籤的位置,matplotlib預約義了多種數字表示的位置。
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,loc參數能夠是2個元素的元組,表示圖例左下角的座標,[0,0] 左下,[0,1] 左上,[1,0] 右下,[1,1] 右上。
ncol:圖例的列數接口
# -*- coding=utf-8 -*- import matplotlib.pyplot as plt import numpy as np if __name__ == "__main__": x1 = np.linspace(0, 2 * np.pi, 100) y1 = np.sin(x1) plt.plot(x1, y1) x2 = x1 = np.linspace(0, 2 * np.pi, 100) y2 = np.cos(x1) plt.plot(x2, y2) plt.legend(['sin(x)', 'cos(x)'], loc=0, ncol=1) plt.show()
標題設置能夠使用plt.title()方法或ax.set_title()方法。
拋物線繪製:
# -*- coding=utf-8 -*- import matplotlib.pyplot as plt import numpy as np if __name__ == "__main__": x = np.arange(-10, 10, 0.1) y = x ** 2 plt.plot(x, y) plt.show()
正弦曲線繪製:
# -*- coding=utf-8 -*- import matplotlib.pyplot as plt import numpy as np if __name__ == "__main__": x = np.linspace(0, 2 * np.pi, 100) y = np.sin(x) plt.plot(x, y) plt.show()
多條曲線繪製:
屢次調用plot函數能夠在圖上繪製多條曲線。
# -*- coding=utf-8 -*- import matplotlib.pyplot as plt import numpy as np if __name__ == "__main__": x1 = np.linspace(0, 2 * np.pi, 100) y1 = np.sin(x1) plt.plot(x1, y1) x2 = x1 = np.linspace(0, 2 * np.pi, 100) y2 = np.cos(x1) plt.plot(x2, y2) plt.show()
能夠在一個plot函數中傳入多對X,Y值,在一個圖中繪製多個曲線。
# -*- coding=utf-8 -*- import matplotlib.pyplot as plt import numpy as np if __name__ == "__main__": x1 = np.linspace(0, 2 * np.pi, 100) y1 = np.sin(x1) x2 = x1 = np.linspace(0, 2 * np.pi, 100) y2 = np.cos(x1) plt.plot(x1, y1, x2, y2) plt.show()
# -*- coding=utf-8 -*- import matplotlib.pyplot as plt import numpy as np if __name__ == "__main__": x = np.random.randint(0, 100, 100) bins = np.arange(0, 101, 10) fig = plt.figure(figsize=(12, 6)) plt.subplot(1, 1, 1) plt.hist(x, bins, color='b', alpha=0.6) plt.show()
# -*- coding=utf-8 -*- import matplotlib.pyplot as plt import numpy as np if __name__ == "__main__": x = [1, 2, 3, 4, 5] y = [2.3, 3.4, 1.2, 6.6, 7.0] fig = plt.figure(figsize=(12, 6)) plt.subplot(1, 1, 1) plt.plot(x, y, color='r', linestyle='-') plt.show()
# -*- coding=utf-8 -*- import matplotlib.pyplot as plt import numpy as np if __name__ == "__main__": x = [1, 2, 3, 4, 5] y = [2.3, 3.4, 1.2, 6.6, 7.0] plt.figure() plt.bar(x, y) plt.title("bar") plt.show()
# -*- coding=utf-8 -*- import matplotlib.pyplot as plt import numpy as np if __name__ == "__main__": y = [2.3, 3.4, 1.2, 6.6, 7.0] plt.figure() plt.pie(y) plt.title('PIE') plt.show()
# -*- coding=utf-8 -*- import matplotlib.pyplot as plt import numpy as np if __name__ == "__main__": n = 1024 X = np.random.normal(0, 1, n) Y = np.random.normal(0, 1, n) T = np.arctan2(Y, X) plt.axes([0.025, 0.025, 0.95, 0.95]) plt.scatter(X, Y, s=75, c=T, alpha=.5) plt.xlim(-1.5, 1.5), plt.xticks([]) plt.ylim(-1.5, 1.5), plt.yticks([]) plt.show()
# -*- coding=utf-8 -*- import matplotlib.pyplot as plt import numpy as np def get_height(x, y): # the height function return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2) if __name__ == "__main__": n = 256 x = np.linspace(-3, 3, n) y = np.linspace(-3, 3, n) X, Y = np.meshgrid(x, y) plt.figure(figsize=(14, 8)) plt.contourf(X, Y, get_height(X, Y), 16, alpah=0.7, cmap=plt.cm.hot) # C = plt.contour(X, Y, get_height(X, Y), 16, color='black', linewidth=.5) # adding label plt.clabel(C, inline=True, fontsize=16) plt.xticks(()) plt.yticks(()) plt.show()
# -*- coding=utf-8 -*- import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D if __name__ == "__main__": fig = plt.figure() ax = Axes3D(fig) 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) Z = np.sin(R) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.hot) ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=plt.cm.hot) ax.set_zlim(-2, 2) plt.show()
圖片加載顯示:
# -*- coding=utf-8 -*- import matplotlib.pyplot as plt if __name__ == "__main__": img = plt.imread('network.png') plt.imshow(img) plt.show()
圖片保存:
# -*- coding=utf-8 -*- import matplotlib.pyplot as plt import numpy as np if __name__ == "__main__": x1 = np.linspace(0, 2 * np.pi, 100) y1 = np.sin(x1) plt.plot(x1, y1) x2 = x1 = np.linspace(0, 2 * np.pi, 100) y2 = np.cos(x1) plt.plot(x2, y2) plt.legend(['sin(x)', 'cos(x)'], loc=0, ncol=1) plt.savefig('test.png') plt.show()
# -*- coding=utf-8 -*- import matplotlib.pyplot as plt import numpy as np if __name__ == "__main__": # 建立一個 8 * 6 點(point)的圖,並設置分辨率爲 80 plt.figure(figsize=(8, 6), dpi=80) # 建立一個新的 1 * 1 的子圖,接下來的圖樣繪製在其中的第 1 塊(也是惟一的一塊) plt.subplot(1, 1, 1) X = np.linspace(-np.pi, np.pi, 256, endpoint=True) C, S = np.cos(X), np.sin(X) # 繪製餘弦曲線,使用藍色的、連續的、寬度爲 1 (像素)的線條 plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-") # 繪製正弦曲線,使用綠色的、連續的、寬度爲 1 (像素)的線條 plt.plot(X, S, color="red", linewidth=2.5, linestyle="-") # 座標軸的範圍 xmin, xmax = X.min(), X.max() ymin, ymax = C.min(), C.max() # 計算座標軸的冗餘 dx = (xmax - xmin) * 0.2 dy = (ymax - ymin) * 0.2 # 設置橫軸的上下限 plt.xlim(xmin - dx, xmax + dx) # 設置縱軸的上下限 plt.ylim(ymin - dy, ymax + dy) # 設置橫軸記號 plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$']) # 設置縱軸記號 plt.yticks([-1, 0, +1], [r'$-1$', r'$0$', r'$+1$']) # 設置座標軸位置 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.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine") plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine") plt.legend(loc='upper left') # 在2pi/3位置作標註 t = 2 * np.pi / 3 plt.plot([t, t], [0, np.cos(t)], color='blue', linewidth=2.5, linestyle="--") plt.scatter([t, ], [np.cos(t), ], 50, color='blue') plt.annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$', xy=(t, np.sin(t)), xycoords='data', xytext=(+10, +30), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) plt.plot([t, t], [0, np.sin(t)], color='red', linewidth=2.5, linestyle="--") plt.scatter([t, ], [np.sin(t), ], 50, color='red') plt.annotate(r'$\cos(\frac{2\pi}{3})=-\frac{1}{2}$', xy=(t, np.cos(t)), xycoords='data', xytext=(-90, -50), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) # 座標軸刻度標籤半透明化 for label in ax.get_xticklabels() + ax.get_yticklabels(): label.set_fontsize(16) label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65)) plt.show()
# -*- coding=utf-8 -*- import matplotlib.pyplot as plt import numpy as np if __name__ == "__main__": fig = plt.figure(figsize=(10, 6)) fig.set_facecolor('white') x = [1, 2, 3, 4, 5, 6, 7] y = [1, 3, 4, 2, 5, 8, 6] # 大圖 left, bottom, width, weight = 0.1, 0.1, 0.8, 0.8 ax = fig.add_axes([left, bottom, width, weight]) ax.plot(x, y, 'r') ax.set_xlabel(r'$X$') ax.set_ylabel(r'$Y$') ax.set_title(r'$BigFigure$') ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') # 左上小圖 left, bottom, width, weight = 0.2, 0.6, 0.25, 0.25 ax1 = fig.add_axes([left, bottom, width, weight]) ax1.plot(y, x, 'b') ax1.set_xlabel(r'$x$') ax1.set_ylabel(r'$y$') ax1.set_title(r'$figure1$') ax1.spines['right'].set_color('none') ax1.spines['top'].set_color('none') plt.show()
能夠直接使用Pandas的Series、DataFrame實例的plot直接進行繪圖。
Series示例以下:
# -*- coding=utf-8 -*- import matplotlib.pyplot as plt import numpy as np import pandas as pd if __name__ == "__main__": # Series繪圖 x = np.linspace(0, 2 * np.pi, 100) # 正弦曲線 y = np.sin(x) s = pd.Series(data=y, index=x) s.plot() plt.show()
DataFrame實例:
# -*- coding=utf-8 -*- import matplotlib.pyplot as plt import numpy as np import pandas as pd if __name__ == "__main__": # DataFrame繪圖 x = np.linspace(0, 2 * np.pi, 100) df = pd.DataFrame(data={'sin': np.sin(x), 'cos': np.cos(x)}, index=x) df.plot() # 取出某列數據進行繪圖 # df['sin'].plot() plt.show()
DataFrame繪製柱狀圖:
# -*- coding=utf-8 -*- import matplotlib.pyplot as plt import numpy as np import pandas as pd if __name__ == "__main__": df = pd.DataFrame(np.random.randint(0, 10, size=(8, 4)), index=list('abcdefgh'), columns=list('ABCD')) ax = df.plot(kind='bar') ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') plt.show()
kind='barh'參數表示繪製水平柱狀圖。