1. 繪制簡單圖形
使用 matplotlib 的pyplot
模塊繪制圖形。看一個 繪制sin函數曲線的例子。
1
2
3
4
5
6
7
8
9
10
|
import matplotlib.pyplot as plt import numpy as np # 生成數據 x = np.arange( 0 , 6 , 0.1 ) # 以0.1為單位,生成0到 6 的數據* y = np.sin(x) # 繪制圖形 plt.plot(x,y) plt.show() |
這里使用NumPy的arange()
方法生成了[0, 0.1, 0.2, … , 5.8, 5.9]的 數據,將其設為x。
對x的各個元素,應用NumPy的sin函數np.sin()
,將x、 y的數據傳給plt.plot方法,然后繪制圖形。
最后,通過plt.show()顯示圖形。 運行上述代碼后,就會顯示如上圖所示的圖形。
2. pyplot的功能
使用 pyplot的添加標題plt.title()
、坐標軸標簽名plt.xlabel()\ plt.ylabel()
和圖例plt.legend()
。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import numpy as np import matplotlib.pyplot as plt # 生成數據 x = np.arange( 0 , 6 , 0.1 ) # 以0.1為單位,生成0到6的數據 y1 = np.sin(x) y2 = np.cos(x) # 繪制圖形 plt.plot(x, y1, label = "sin" ) plt.plot(x, y2, linestyle = "--" , label = "cos" ) # 用虛線繪制 plt.xlabel( "x" ) # x軸標簽 plt.ylabel( "y" ) # y軸標簽 plt.title( 'sin & cos' ) # 標題 plt.legend() #顯示圖例 plt.show() |
3. 顯示圖像
pyplot中還提供了用于顯示圖像的方法imshow()
。
使用 matplotlib.image
模塊的imread()
方法讀入圖像。
1
2
3
4
5
6
7
|
import matplotlib.pyplot as plt from matplotlib.image import imread img = imread(r 'D:\plant\plant_1.jpg' ) # 讀入圖像,讀者根據自己的環境,變更文件名或文件路徑(絕對或相對路徑,注意路徑名不能出現中文) plt.imshow(img) plt.show() |
到此這篇關于使用matplotlib的pyplot模塊繪圖的實現示例的文章就介紹到這了,更多相關matplotlib pyplot模塊繪圖內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/m0_46079750/article/details/107243064