1.畫最簡單的直線圖
代碼如下:
1
2
3
4
5
6
7
8
|
import numpy as np import matplotlib.pyplot as plt x = [ 0 , 1 ] y = [ 0 , 1 ] plt.figure() plt.plot(x,y) plt.savefig( "easyplot.jpg" ) |
結果如下:
代碼解釋:
1
2
3
4
5
6
7
8
9
|
#x軸,y軸 x = [ 0 , 1 ] y = [ 0 , 1 ] #創建繪圖對象 plt.figure() #在當前繪圖對象進行繪圖(兩個參數是x,y軸的數據) plt.plot(x,y) #保存圖象 plt.savefig( "easyplot.jpg" ) |
2.給圖加上標簽與標題
上面的圖沒有相應的X,Y軸標簽說明與標題
在上述代碼基礎上,可以加上這些內容
代碼如下:
1
2
3
4
5
6
7
8
9
10
11
|
import numpy as np import matplotlib.pyplot as plt x = [ 0 , 1 ] y = [ 0 , 1 ] plt.figure() plt.plot(x,y) plt.xlabel( "time(s)" ) plt.ylabel( "value(m)" ) plt.title( "A simple plot" ) |
結果如下:
代碼解釋:
1
2
3
|
plt.xlabel( "time(s)" ) #X軸標簽 plt.ylabel( "value(m)" ) #Y軸標簽 plt.title( "A simple plot" ) #標題 |
3.畫sinx曲線
代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
# -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt #設置x,y軸的數值(y=sinx) x = np.linspace( 0 , 10 , 1000 ) y = np.sin(x) #創建繪圖對象,figsize參數可以指定繪圖對象的寬度和高度,單位為英寸,一英寸=80px plt.figure(figsize = ( 8 , 4 )) #在當前繪圖對象中畫圖(x軸,y軸,給所繪制的曲線的名字,畫線顏色,畫線寬度) plt.plot(x,y,label = "$sin(x)$" ,color = "red" ,linewidth = 2 ) #X軸的文字 plt.xlabel( "Time(s)" ) #Y軸的文字 plt.ylabel( "Volt" ) #圖表的標題 plt.title( "PyPlot First Example" ) #Y軸的范圍 plt.ylim( - 1.2 , 1.2 ) #顯示圖示 plt.legend() #顯示圖 plt.show() #保存圖 plt.savefig( "sinx.jpg" ) |
結果如下:
4.畫折線圖
代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
# -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt #X軸,Y軸數據 x = [ 0 , 1 , 2 , 3 , 4 , 5 , 6 ] y = [ 0.3 , 0.4 , 2 , 5 , 3 , 4.5 , 4 ] plt.figure(figsize = ( 8 , 4 )) #創建繪圖對象 plt.plot(x,y, "b--" ,linewidth = 1 ) #在當前繪圖對象繪圖(X軸,Y軸,藍色虛線,線寬度) plt.xlabel( "Time(s)" ) #X軸標簽 plt.ylabel( "Volt" ) #Y軸標簽 plt.title( "Line plot" ) #圖標題 plt.show() #顯示圖 plt.savefig( "line.jpg" ) #保存圖 |
結果如下:
總結
以上就是本文關于python繪制簡單折線圖代碼示例的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題。如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:http://blog.csdn.net/wangyajie_11/article/details/53816768