Matplotlib學習---用matplotlib畫階梯圖(step plot)


這里利用Nathan Yau所著的《鮮活的數據:數據可視化指南》一書中的數據,學習畫圖。

 

數據地址:http://datasets.flowingdata.com/us-postage.csv 

 

准備工作:先導入matplotlib和pandas,用pandas讀取csv文件,然后創建一個圖像和一個坐標軸

import pandas as pd
from matplotlib import pyplot as plt
postage=pd.read_csv(r"http://datasets.flowingdata.com/us-postage.csv")
fig,ax=plt.subplots()

 

先來看看這個數據文件:

   Year  Price
0  1991   0.29
1  1995   0.32
2  1999   0.33
3  2001   0.34
4  2002   0.37
5  2006   0.39
6  2007   0.41
7  2008   0.42
8  2009   0.44
9  2010   0.44

這個數據很簡單,展示的是從1991年-2010年美國郵費的變化。

 

讓我們來畫一個階梯圖,展現郵費的變化過程。

 

階梯圖: ax.step(x,y)

 

代碼如下:

import pandas as pd
from matplotlib import pyplot as plt
postage=pd.read_csv(r"http://datasets.flowingdata.com/us-postage.csv")
fig,ax=plt.subplots(figsize=(10,4))

ax.step(postage["Year"],postage["Price"],where='post')
ax.set_title("US Postage Fee") #設置標題
ax.set_xticks([i for i in postage["Year"]]) #設置x軸刻度
ax.set_yticks([]) #去除y軸刻度
#去除邊框
ax.spines["top"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.spines["left"].set_visible(False)
ax.spines["right"].set_visible(False)
#添加文字注釋
for i,j in zip(postage["Year"],postage["Price"]):
    ax.text(x=i,y=j+0.003,s=j)
fig.tight_layout()

plt.show()

 

圖像如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM