Python折線圖簡單小實例

找到了一份非常有意思的python學習資料 Learning Python: Part 2 – Visualizing the NBA Draft。主要內容是探索1966到2014年NBA選秀的數據。數據集可以利用 Learning Python: Part 1- Scraping and Cleaning the NBA Draft 部分的內容獲得,同時這部分內容也是非常好的python爬蟲學習素材。 本文主要記錄自己重複以上教程的筆記。

原文內容相對較長,自己將其分成幾個部分分別記錄

第一部分:折線圖

導入需要用到的模組
import numpy as np  import pandas as pd  import matplotlib.pyplot as plt  import seaboarn as sns  
讀入數據並整理成作圖需要的格式

折線圖用來展示每年所有參加選秀的運動員的贏球貢獻值(Win shares Per 48 minutes)的平均值。橫軸為年份,縱軸為贏球貢獻值

draft_df = pd.read_csv("draft_data_1996_to_2014.csv",index_col=0)  #index_col參數的作用暫時還不太清楚  draft_df.head()  

對於數據整理的簡單理解 比如在我們自己的實驗中,對實驗材料進行三種不同的處理,每個處理三次重複,數據記錄為

    Treatment  Values  0         A     1.1  1         A     1.2  2         A     1.0  3         B     2.2  4         B     2.4  5         B     2.5  6         C     3.6  7         C     3.8  8         C     3.9  

現在我想通過折線圖展示不同處理的變化趨勢,縱坐標為每個處理的均值,原文提供了兩種實現方式

第一種:利用列表生成式
df = pd.read_csv("example_data/example_data.csv")  Values_avg = [df[df["Treatment"] == yr ]["Values"].mean() for yr in df.Treatment.unique()]  Values_avg  
第二種:直接利用pandas的groupby()函數
df.groupby("Treatment").Values.mean()  

接下來直接利用groupby()函數獲得需要的數據

WS48_yrly_avg = draft_df.groupby("Draft_Yr").WS_per_48.mean()  X_values = draft_df.Draft_Yr.unique()  Y_values = WS48_yrly_avg  

繪圖程式碼

plt.figure(figsize=(12,9))  Out[33]: <matplotlib.figure.Figure at 0x2458ca59ac8>    title = ('Average Career Win Sahres Per 48 minutes by Draft Year (1966-2014)')    plt.title(title,fontsize=20)  Out[35]: Text(0.5,1,'Average Career Win Sahres Per 48 minutes by Draft Year (1966-2014)')    plt.ylabel('Win Shares Per 48 minutes',fontsize=18)  Out[36]: Text(0,0.5,'Win Shares Per 48 minutes')    plt.xlim(1966,2014.5)  Out[37]: (1966, 2014.5)    plt.ylim(0,0.08)  Out[38]: (0, 0.08)    plt.grid(axis='y',color="grey",linestyle='--',lw=0.5,alpha=0.5)    plt.tick_params(axis='both',labelsize=14)    import seaborn as sns    sns.despine(left=True,bottom=True)    plt.plot(X_values,Y_values)  Out[43]: [<matplotlib.lines.Line2D at 0x2458dc40cf8>]    plt.text(1966,-0.012,'The original content :http://savvastjortjoglou.com/nba-draft-part02-visualizing.htmlnPorter: MingYan',fontsize=12)  Out[44]: Text(1966,-0.012,'The original content :http://savvastjortjoglou.com/nba-draft-part02-visualizing.htmlnPorter: MingYan')    plt.savefig("Line_chart_1.png")  

結果

Line_chart_1.png