(給Python開發者加星標,提升Python技能)
來源:逐夢er
https://zhumenger.blog.csdn.net/article/details/106530281
【導語】:出色的數據可視化,會讓你的數據分析等工作錦上添花,讓人印(升)象(職)深(加)刻(薪)。matplotlib是python優秀的數據可視化庫,python數據分析必備利器,本文專門為你整理了matplotlib詳細使用方法,來學習吧!
--- 以下是正文 ---
數據可視化非常重要,因為錯誤或不充分的數據表示方法可能會毀掉原本很出色的數據分析工作。
matplotlib 庫是專門用於開發2D圖表(包括3D圖表)的,突出優點:
使用起來極為簡單。
以漸進、交互式方式實現數據可視化。
表達式和文本使用LaTeX排版。
對圖像元素控制力強。
可輸出PNG、PDF、SVG和EPS等多種格式。
安裝或者
matplotlib 架構
matplotlib 的主要任務之一,就是提供一套表示和操作圖形對象(主要對象)以及它的內部對象的函數和工具。其不僅可以處理圖形,還提供事件處理工具,具有為圖形添加動畫效果的能力。有了這些附加功能,matplotlib 就能生成以鍵盤按鍵或滑鼠移動觸發的事件的交互式圖表。
從邏輯上來講,matplotlib 的整體架構為3層,各層之間單向通信:
Scripting (腳本)層。
Artist (表現)層。
Backend (後端)層。
一、matplotlib的基本用法import numpy as npimport matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 30) y = np.sin(x)print('x = ', x)print('y = ', y)輸出:
x = [-3.14159265 -2.92493109 -2.70826953 -2.49160797 -2.2749464 -2.05828484 -1.84162328 -1.62496172 -1.40830016 -1.19163859 -0.97497703 -0.75831547 -0.54165391 -0.32499234 -0.10833078 0.10833078 0.32499234 0.54165391 0.75831547 0.97497703 1.19163859 1.40830016 1.62496172 1.84162328 2.05828484 2.2749464 2.49160797 2.70826953 2.92493109 3.14159265]y = [-1.22464680e-16 -2.14970440e-01 -4.19889102e-01 -6.05174215e-01 -7.62162055e-01 -8.83512044e-01 -9.63549993e-01 -9.98533414e-01 -9.86826523e-01 -9.28976720e-01 -8.27688998e-01 -6.87699459e-01 -5.15553857e-01 -3.19301530e-01 -1.08119018e-01 1.08119018e-01 3.19301530e-01 5.15553857e-01 6.87699459e-01 8.27688998e-01 9.28976720e-01 9.86826523e-01 9.98533414e-01 9.63549993e-01 8.83512044e-01 7.62162055e-01 6.05174215e-01 4.19889102e-01 2.14970440e-01 1.22464680e-16]plt.figure() plt.plot(x, y) plt.show()import numpy as npimport matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 100) y = np.sin(x)linear_y = 0.2 * x + 0.1
plt.figure(figsize = (8, 6))
plt.plot(x, y)plt.plot(x, linear_y, color = "red", linestyle = '--')
plt.title('y = sin(x) and y = 0.2x + 0.1') plt.xlabel('x') plt.ylabel('y')
plt.show()import numpy as npimport matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 100) y = np.sin(x)linear_y = 0.2 * x + 0.1
plt.figure(figsize = (8, 6))
plt.plot(x, y)plt.plot(x, linear_y, color = "red", linestyle = '--')
plt.title('y = sin(x) and y = 0.2x + 0.1') plt.xlabel('x') plt.ylabel('y') plt.xlim(-np.pi, np.pi)plt.ylim(-1, 1)
x_value_range = np.linspace(-np.pi, np.pi, 5)x_value_strs = [r'$\pi$', r'$-\frac{\pi}{2}$', r'$0$', r'$\frac{\pi}{2}$', r'$\pi$']plt.xticks(x_value_range, x_value_strs)plt.show()import numpy as npimport matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 100)y = np.sin(x)linear_y = 0.2 * x + 0.1
plt.figure(figsize = (8, 6))
plt.plot(x, y)plt.plot(x, linear_y, color = "red", linestyle = '--')
plt.title('y = sin(x) and y = 0.2x + 0.1')plt.xlabel('x') plt.ylabel('y') plt.xlim(-np.pi, np.pi)plt.ylim(-1, 1)
x_value_range = np.linspace(-np.pi, np.pi, 5)x_value_strs = [r'$\pi$', r'$-\frac{\pi}{2}$', r'$0$', r'$\frac{\pi}{2}$', r'$\pi$']plt.xticks(x_value_range, x_value_strs)
ax = plt.gca() ax.spines['right'].set_color('none') ax.spines['top'].set_color('none')
ax.spines['bottom'].set_position(('data', 0)) ax.spines['left'].set_position(('data', 0))
plt.show()使用xticks()和yticks()函數替換軸標籤,分別為每個函數傳入兩列數值。第一個列表存儲刻度的位置,第二個列表存儲刻度的標籤。
import numpy as npimport matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 100)y = np.sin(x)linear_y = 0.2 * x + 0.1
plt.figure(figsize = (8, 6))
plt.plot(x, y, label = "y = sin(x)")plt.plot(x, linear_y, color = "red", linestyle = '--', label = 'y = 0.2x + 0.1')
plt.title('y = sin(x) and y = 0.2x + 0.1')plt.xlabel('x') plt.ylabel('y') plt.xlim(-np.pi, np.pi)plt.ylim(-1, 1)
x_value_range = np.linspace(-np.pi, np.pi, 5)x_value_strs = [r'$\pi$', r'$-\frac{\pi}{2}$', r'$0$', r'$\frac{\pi}{2}$', r'$\pi$']plt.xticks(x_value_range, x_value_strs)
ax = plt.gca() ax.spines['right'].set_color('none')ax.spines['top'].set_color('none')
ax.spines['bottom'].set_position(('data', 0)) ax.spines['left'].set_position(('data', 0))
plt.legend(loc = 'lower right', fontsize = 12)plt.show()legend方法中的loc 參數可選設置
位置字符串位置編號位置表述『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正中間二、柱狀圖使用的方法:plt.bar
import numpy as npimport matplotlib.pyplot as plt
plt.figure(figsize = (16, 12))x = np.array([1, 2, 3, 4, 5, 6, 7, 8])y = np.array([3, 5, 7, 6, 2, 6, 10, 15])plt.plot(x, y, 'r', lw = 5)
x = np.array([1, 2, 3, 4, 5, 6, 7, 8])y = np.array([13, 25, 17, 36, 21, 16, 10, 15])plt.bar(x, y, 0.2, alpha = 1, color='b') plt.show()有的時候柱狀圖會出現在x軸的倆側,方便進行比較,代碼實現如下:
import numpy as npimport matplotlib.pyplot as plt
plt.figure(figsize = (16, 12))n = 12x = np.arange(n) # 按順序生成從12以內的數字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)
# 設置柱狀圖的顏色以及邊界顏色#+y表示在x軸的上方 -y表示在x軸的下方plt.bar(x, +y1, facecolor = '#9999ff', edgecolor = 'white')plt.bar(x, -y2, facecolor = '#ff9999', edgecolor = 'white')
plt.xlim(-0.5, n) # 設置x軸的範圍,plt.xticks(()) # 可以通過設置刻度為空,消除刻度plt.ylim(-1.25, 1.25) # 設置y軸的範圍plt.yticks(())
# plt.text()在圖像中寫入文本,設置位置,設置文本,ha設置水平方向對其方式,va設置垂直方向對齊方式for x1, y in zip(x, y2): plt.text(x1, -y - 0.05, '%.2f' % y, ha = 'center', va = 'top')for x1, y in zip(x, y1): plt.text(x1, y + 0.05, '%.2f' % y, ha = 'center', va = 'bottom')plt.show()三、散點圖
import numpy as npimport matplotlib.pyplot as pltN = 50x = np.random.rand(N)y = np.random.rand(N)colors = np.random.rand(N)area = np.pi * (15 * np.random.rand(N))**2plt.scatter(x, y, s = area,c = colors, alpha = 0.8)
plt.show()
四、等高線圖import matplotlib.pyplot as pltimport numpy as np
def f(x, y): return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)
n = 256x = np.linspace(-3, 3, n)y = np.linspace(-3, 3, n)X, Y = np.meshgrid(x, y) line_num = 10
plt.figure(figsize = (16, 12))
C = plt.contour(X, Y, f(X, Y), line_num, colors = 'black', linewidths = 0.5) plt.clabel(C, inline = True, fontsize = 12)
plt.contourf(X, Y, f(X, Y), line_num, alpha = 0.75, cmap = plt.cm.hot)
plt.show()五、處理圖片import matplotlib.pyplot as pltimport matplotlib.image as mpimg import matplotlib.cm as cm
plt.figure(figsize = (16, 12))img = mpimg.imread('image/fuli.jpg')print(img) print(img.shape)
plt.imshow(img, cmap = 'hot')plt.colorbar() plt.show()[[[ 11 23 63] [ 12 24 64] [ 1 13 55] ... [ 1 12 42] [ 1 12 42] [ 1 12 42]]
[[ 19 31 71] [ 3 15 55] [ 0 10 52] ... [ 0 11 39] [ 0 11 39] [ 0 11 39]]
[[ 22 34 74] [ 3 15 55] [ 7 19 61] ... [ 0 11 39] [ 0 11 39] [ 0 11 39]]
...
[[ 84 125 217] [ 80 121 213] [ 78 118 214] ... [ 58 90 191] [ 54 86 187] [ 53 85 186]]
[[ 84 124 220] [ 79 119 215] [ 78 117 218] ... [ 55 87 188] [ 55 87 188] [ 55 87 188]]
[[ 83 121 220] [ 80 118 219] [ 83 120 224] ... [ 56 88 189] [ 58 90 191] [ 59 91 192]]](728, 516, 3)利用numpy矩陣得到圖片
import matplotlib.pyplot as pltimport matplotlib.cm as cm import numpy as np
size = 8a = np.linspace(0, 1, size ** 2).reshape(size, size)
plt.figure(figsize = (16, 12))plt.imshow(a)plt.show()六、3D圖import numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(figsize = (16, 12))ax = fig.add_subplot(111, projection = '3d')
x = np.arange(-4, 4, 0.25)y = np.arange(-4, 4, 0.25)X, Y = np.meshgrid(x, y) Z = np.sqrt(X ** 2 + Y ** 2)
ax.plot_surface(X, Y, Z, rstride = 1, cstride = 1, cmap = plt.get_cmap('rainbow'))plt.show()以上是matplotlib基於測試數據的數據可視化,結合實際項目中數據,代碼稍加修改,即可有讓人印象深刻的效果。
- EOF -
覺得本文對你有幫助?請分享給更多人
關注「Python開發者」加星標,提升Python技能
點讚和在看就是最大的支持❤️