Python繪圖庫Matplotlib初識
最近刷到了很多數據可視化的視頻,然后今天看視頻課也正好看到了python的Matplotlib庫講解。課程講的很有趣,但是有同學覺得還不夠小白。看到同學們的評論,我覺得這就是熱心群眾挺身而出的時候了。
以輸出倒逼輸入,沖。另外找Matplotlib參考資料的時候我還發現了國家統計局-國家數據網站,感覺這波學完能當場學以致用,統計局網站下載一些數據稍微調試下,可以直接弄成數據可視化的視頻。
1、代碼行級注釋
注:和視頻課老師上課演示的代碼不完全一致,存在部分,但是大致結構沒動
1 import pandas as pd 2 import matplotlib.pyplot as plt 3 import matplotlib.ticker as ticker 4 import matplotlib.animation as animation 5 6 # 導入數據 7 # pandas獲取City.csv文件中name、group、year、value四個字段 8 df = pd.read_csv('./City.csv', usecols=['name', 'group', 'year', 'value']) 9 10 # 設置顏色 11 # 映射函數方式來構造字典 12 colors = dict(zip(["India", "Europe", "Asia", "Latin America", "Middle East", "North America", "Africa"], ["#adb0ff", "#ffb3ff", "#90d595", "#e48381", "#aafbff", "#f7bb5f", "#eafb50"])) 13 # 創建城市與洲的對應關系的字典 14 group_lk = df.set_index('name')['group'].to_dict() 15 16 # 創建對象,繪圖展示窗口大小設置 17 # 此處等價於fig = plt.figure(figsize=(15, 8));ax = fig.add_subplot(1,1,1) 18 fig, ax = plt.subplots(figsize=(15, 8)) 19 20 21 # 畫單年份橫着的條形圖 22 def draw(current_year): 23 # 獲取year為current_year,按value升序排序,獲取最后10組數據 24 dff = df[df['year'].eq(current_year)].sort_values(by='value', ascending=True).tail(10) 25 # 清除主坐標軸數據 26 ax.clear() 27 # 遍歷dff中數據,以其中name為y軸(縱軸)數據,以其中value為x軸(橫軸)數據 28 # 通過城市與洲的對應關系獲取洲,再通過洲與顏色對應關系獲取顏色,此顏色為數據顏色 29 ax.barh(dff['name'], dff['value'], color=[colors[group_lk[x]] for x in dff['name']]) 30 31 # 獲取dff中最大的value除以200作為參考系,方便后續調整標簽相對位置 32 dx = dff['value'].max() / 200 33 # 遍歷dff的value和name組成的元組 34 # 對每一行條形圖的顯示效果進行修飾,在行盡頭添加name,group,value 35 for i, (value, name) in enumerate(zip(dff['value'], dff['name'])): 36 # 在(value - dx,i)坐標處添加標簽,標簽內容為name,居右對齊,居下對齊 37 ax.text(value - dx, i, name, size=14, weight=600, ha='right', va='bottom') 38 # 在(value - dx,i- .25)坐標處添加標簽,標簽內容為name,居右對齊,居下對齊 39 ax.text(value - dx, i - .25, group_lk[name], size=10, color='#444444', ha='right', va='baseline') 40 # 在(value + dx,i)坐標處添加標簽,標簽內容為格式化的value(浮點數保留0位小數) 41 ax.text(value + dx, i, f'{value:,.0f}', size=14, ha='left', va='center') 42 43 # 使用Axes坐標系【左下角為(0,0)右上角為(1,1)】,在(1,0.4)坐標處添加標簽,標簽內容為current_year 44 ax.text(1, 0.4, current_year, transform=ax.transAxes, color='#777777', size=46, ha='right', weight=800) 45 # 使用Axes坐標系【左下角為(0,0)右上角為(1,1)】,在(0,1.15)坐標處添加標簽,標簽內容為Population (thousands) 46 ax.text(0, 1.06, 'Population (thousands)', transform=ax.transAxes, size=12, color='#777777') 47 48 # 設置x軸精度,格式化為浮點數保留0位小數 49 ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}')) 50 # 設置x軸位置,放置到頂部 51 ax.xaxis.set_ticks_position('top') 52 # 設置x軸顏色及大小 53 ax.tick_params(axis='x', colors='#777777', labelsize=12) 54 55 # 設置y軸坐標軸為空 56 ax.set_yticks([]) 57 58 # 內邊距設置 59 ax.margins(0, 0.01) 60 61 # 設置x軸上的刻度線 62 ax.grid(which='major', axis='x', linestyle='-') 63 # 刻度線顯示在頁面的最下層 64 ax.set_axisbelow(True) 65 66 # 使用Axes坐標系【左下角為(0,0)右上角為(1,1)】,在(0,1.15)坐標處添加標簽,標簽內容為'The most populous cities in the world from 2000 to 2018',居左對齊,居上對齊 67 ax.text(0, 1.15, 'The most populous cities in the world from 2000 to 2018', transform=ax.transAxes, size=24, weight=600, ha='left', va='top') 68 69 # 去掉邊框 70 plt.box(False) 71 72 73 # 繪制動圖,繪制畫布為fig,自定義函數為draw,傳值給draw參數為2000~2018;即展示效果為2000~2018年條形圖的變化 74 animation = animation.FuncAnimation(fig, draw, frames=range(2000, 2019)) 75 76 # 顯示動態柱狀圖 77 plt.show() 78
2、遇到過的問題
問題:pycharm中程序執行無報錯,但是animation.FuncAnimation無法播放,只顯示一張白畫布
解決:按照這邊文章:解決:pycharm中動畫函數animation.FuncAnimation不起作用,修改pycharm配置即可
3、參考資料
(2)解決:pycharm中動畫函數animation.FuncAnimation不起作用
(3)Matplotlib官網
4、個人執行結果