tft每日頭條

 > 圖文

 > python 如何安裝matplotlib

python 如何安裝matplotlib

圖文 更新时间:2025-02-02 18:44:07

數據可視化非常重要,因為錯誤或不充分的數據表示方法可能會毀掉原本很出色的數據分析工作。

matplotlib 庫是專門用于開發2D圖表(包括3D圖表)的,突出優點:

  • 使用起來極為簡單。
  • 以漸進、交互式方式實現數據可視化。
  • 表達式和文本使用LaTeX排版。
  • 對圖像元素控制力強。
  • 可輸出PNG、PDF、SVG和EPS等多種格式。

安裝

condainstallmatplotlib

或者

pipinstallmatplotlib

matplotlib 架構

matplotlib 的主要任務之一,就是提供一套表示和操作圖形對象(主要對象)以及它的内部對象的函數和工具。其不僅可以處理圖形,還提供事件處理工具,具有為圖形添加動畫效果的能力。有了這些附加功能,matplotlib 就能生成以鍵盤按鍵或鼠标移動觸發的事件的交互式圖表。

從邏輯上來講,matplotlib 的整體架構為3層,各層之間單向通信:

  • Scripting (腳本)層。
  • Artist (表現)層。
  • Backend (後端)層。

一、matplotlib的基本用法

import numpy as np import matplotlib.pyplot as plt x = np.linspace(-np.pi, np.pi, 30) # 在區間内生成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-011.22464680e-16]

  • 畫一條曲線

plt.figure() # 創建一個新的窗口 plt.plot(x, y) # 畫一個x與y相關的曲線 plt.show()# 顯示圖像

python 如何安裝matplotlib(基于Python的matplotlib基礎介紹)1

  • 畫多條曲線以及添加坐标軸和标簽

import numpy as np import matplotlib.pyplot as plt x = np.linspace(-np.pi, np.pi, 100) # 在區間内生成21個等差數 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()

python 如何安裝matplotlib(基于Python的matplotlib基礎介紹)2

  • 指定坐标範圍 and 設置坐标軸刻度

import numpy as np import matplotlib.pyplot as plt x = np.linspace(-np.pi, np.pi, 100) # 在區間内生成21個等差數 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軸的刻度 # plt.xticks(np.linspace(-np.pi, np.pi, 5)) 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()#顯示圖像

python 如何安裝matplotlib(基于Python的matplotlib基礎介紹)3

  • 定義原點在中心的坐标軸

import numpy as np import 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) # plt.xticks(np.linspace(-np.pi, np.pi, 5)) 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)) # 将下方的坐标軸設置到y = 0的位置 ax.spines['left'].set_position(('data', 0)) # 将左方的坐标軸設置到 x = 0 的位置 plt.show() # 顯示圖像

python 如何安裝matplotlib(基于Python的matplotlib基礎介紹)4

  • legend圖例

使用xticks()和yticks()函數替換軸标簽,分别為每個函數傳入兩列數值。第一個列表存儲刻度的位置,第二個列表存儲刻度的标簽。

import numpy as np import 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) # plt.xticks(np.linspace(-np.pi, np.pi, 5)) 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()

python 如何安裝matplotlib(基于Python的matplotlib基礎介紹)5

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 np import 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()

python 如何安裝matplotlib(基于Python的matplotlib基礎介紹)6

有的時候柱狀圖會出現在x軸的倆側,方便進行比較,代碼實現如下:

import numpy as np import matplotlib.pyplot as plt plt.figure(figsize = (16, 12)) n = 12 x = 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()

python 如何安裝matplotlib(基于Python的matplotlib基礎介紹)7

三、散點圖

import numpy as np import matplotlib.pyplot as plt N = 50 x = np.random.rand(N) y = np.random.rand(N) colors = np.random.rand(N) area = np.pi * (15 * np.random.rand(N))**2 plt.scatter(x, y, s = area,c = colors, alpha = 0.8) plt.show()

python 如何安裝matplotlib(基于Python的matplotlib基礎介紹)8

四、等高線圖

import matplotlib.pyplot as plt import numpy as np 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) # 生成網格坐标 将x軸與y軸正方形區域的點全部獲取 line_num = 10 # 等高線的數量 plt.figure(figsize = (16, 12)) #contour 生成等高線的函數 #前倆個參數表示點的坐标,第三個參數表示等成等高線的函數,第四個參數表示生成多少個等高線 C = plt.contour(X, Y, f(X, Y), line_num, colors = 'black', linewidths = 0.5) # 設置顔色和線段的寬度 plt.clabel(C, inline = True, fontsize = 12) # 得到每條等高線确切的值 # 填充顔色, cmap 表示以什麼方式填充,hot表示填充熱量的顔色 plt.contourf(X, Y, f(X, Y), line_num, alpha = 0.75, cmap = plt.cm.hot) plt.show()

python 如何安裝matplotlib(基于Python的matplotlib基礎介紹)9

五、處理圖片

import matplotlib.pyplot as plt import matplotlib.image as mpimg # 導入處理圖片的庫 import matplotlib.cm as cm # 導入處理顔色的庫colormap plt.figure(figsize = (16, 12)) img=mpimg.imread('image/fuli.jpg')#讀取圖片 print(img) # numpy數據 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)

python 如何安裝matplotlib(基于Python的matplotlib基礎介紹)10

利用numpy矩陣得到圖片

import matplotlib.pyplot as plt import matplotlib.cm as cm # 導入處理顔色的庫colormap import numpy as np size = 8 # 得到一個8*8數值在(0, 1)之間的矩陣 a = np.linspace(0, 1, size ** 2).reshape(size, size) plt.figure(figsize = (16, 12)) plt.imshow(a) plt.show()

python 如何安裝matplotlib(基于Python的matplotlib基礎介紹)11

六、3D圖

import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # 導入Axes3D對象 fig = plt.figure(figsize = (16, 12)) ax = fig.add_subplot(111, projection = '3d') # 得到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()

python 如何安裝matplotlib(基于Python的matplotlib基礎介紹)12

以上是matplotlib基于測試數據的數據可視化,結合實際項目中數據,代碼稍加修改,即可有讓人印象深刻的效果

,

更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!

查看全部

相关圖文资讯推荐

热门圖文资讯推荐

网友关注

Copyright 2023-2025 - www.tftnews.com All Rights Reserved