Python圖表屬性



Python擁有優秀的用於資料視覺化的庫。結合Pandasnumpymatplotlib,可以建立幾乎所有型別的視覺化圖表。本章我們將開始學習一些簡單的圖表及其各種屬性。

建立圖表

我們使用numpy庫建立建立圖表所需的數字,並使用matplotlib中的pyplot方法繪製實際圖表。

import numpy as np 
import matplotlib.pyplot as plt 

x = np.arange(0,10) 
y = x ^ 2 
#Simple Plot
plt.plot(x,y)

輸出如下:

chartprop1.png

軸標籤

我們可以使用庫中的適當方法為軸新增標籤,併為圖表新增標題,如下所示。

import numpy as np 
import matplotlib.pyplot as plt 

x = np.arange(0,10) 
y = x ^ 2 
#Labeling the Axes and Title
plt.title("Graph Drawing") 
plt.xlabel("Time") 
plt.ylabel("Distance") 
#Simple Plot
plt.plot(x,y)

輸出如下:

chartprop2.png

格式化線型和顏色

可以使用庫中的適當方法指定圖表中線的樣式和顏色,如下所示。

import numpy as np 
import matplotlib.pyplot as plt 

x = np.arange(0,10) 
y = x ^ 2 
#Labeling the Axes and Title
plt.title("Graph Drawing") 
plt.xlabel("Time") 
plt.ylabel("Distance") 

# Formatting the line colors
plt.plot(x,y,'r')

# Formatting the line type  
plt.plot(x,y,'>') 

輸出如下:

chartprop3.png

儲存圖表檔案

可以使用庫中的適當方法將圖表儲存為不同的影像檔案格式,如下所示。

import numpy as np 
import matplotlib.pyplot as plt 

x = np.arange(0,10) 
y = x ^ 2 
#Labeling the Axes and Title
plt.title("Graph Drawing") 
plt.xlabel("Time") 
plt.ylabel("Distance") 

# Formatting the line colors
plt.plot(x,y,'r')

# Formatting the line type  
plt.plot(x,y,'>') 

# save in pdf formats
plt.savefig('timevsdist.pdf', format='pdf')

以上程式碼在Python環境的預設路徑下建立pdf檔案。

廣告
© . All rights reserved.