1. 繪制簡(jiǎn)單圖形
使用 matplotlib 的pyplot
模塊繪制圖形。看一個(gè) 繪制sin函數(shù)曲線的例子。
1
2
3
4
5
6
7
8
9
10
|
import matplotlib.pyplot as plt import numpy as np # 生成數(shù)據(jù) x = np.arange( 0 , 6 , 0.1 ) # 以0.1為單位,生成0到 6 的數(shù)據(jù)* y = np.sin(x) # 繪制圖形 plt.plot(x,y) plt.show() |
這里使用NumPy的arange()
方法生成了[0, 0.1, 0.2, … , 5.8, 5.9]的 數(shù)據(jù),將其設(shè)為x。
對(duì)x的各個(gè)元素,應(yīng)用NumPy的sin函數(shù)np.sin()
,將x、 y的數(shù)據(jù)傳給plt.plot方法,然后繪制圖形。
最后,通過(guò)plt.show()顯示圖形。 運(yùn)行上述代碼后,就會(huì)顯示如上圖所示的圖形。
2. pyplot的功能
使用 pyplot的添加標(biāo)題plt.title()
、坐標(biāo)軸標(biāo)簽名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 # 生成數(shù)據(jù) x = np.arange( 0 , 6 , 0.1 ) # 以0.1為單位,生成0到6的數(shù)據(jù) 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軸標(biāo)簽 plt.ylabel( "y" ) # y軸標(biāo)簽 plt.title( 'sin & cos' ) # 標(biāo)題 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' ) # 讀入圖像,讀者根據(jù)自己的環(huán)境,變更文件名或文件路徑(絕對(duì)或相對(duì)路徑,注意路徑名不能出現(xiàn)中文) plt.imshow(img) plt.show() |
到此這篇關(guān)于使用matplotlib的pyplot模塊繪圖的實(shí)現(xiàn)示例的文章就介紹到這了,更多相關(guān)matplotlib pyplot模塊繪圖內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/m0_46079750/article/details/107243064