Python - 圖表樣式



在 Python 中建立的圖表可以透過使用圖表庫中的一些適當方法進行進一步的樣式設定。在本課中,我們將瞭解註釋、圖例和圖表背景的實現。我們將繼續使用上一章的程式碼,並對其進行修改以將這些樣式新增到圖表中。

添加註釋

很多時候,我們需要透過突出顯示圖表中的特定位置來註釋圖表。在下面的示例中,我們透過在這些點添加註釋來指示圖表中值的急劇變化。

import numpy as np 
from matplotlib import pyplot as plt 

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

#Annotate
plt.annotate(xy=[2,1], s='Second Entry') 
plt.annotate(xy=[4,6], s='Third Entry') 

輸出如下所示:

chartstyle1.png

新增圖例

有時我們需要繪製多條線的圖表。圖例的使用表示與每條線相關的含義。在下圖中,我們有 3 條線以及相應的圖例。

import numpy as np 
from matplotlib import pyplot as plt 

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

#Annotate
plt.annotate(xy=[2,1], s='Second Entry') 
plt.annotate(xy=[4,6], s='Third Entry') 
# Adding Legends
plt.plot(x,z)
plt.plot(x,t)
plt.legend(['Race1', 'Race2','Race3'], loc=4) 

輸出如下所示:

chartstyle2.png

圖表呈現樣式

我們可以使用樣式包中的不同方法修改圖表的呈現樣式。

import numpy as np 
from matplotlib import pyplot as plt 

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

#Annotate
plt.annotate(xy=[2,1], s='Second Entry') 
plt.annotate(xy=[4,6], s='Third Entry') 
# Adding Legends
plt.plot(x,z)
plt.plot(x,t)
plt.legend(['Race1', 'Race2','Race3'], loc=4) 

#Style the background
plt.style.use('fast')
plt.plot(x,z)

輸出如下所示:

chartstyle3.png
廣告

© . All rights reserved.