matplotlibの基礎知識
matplotlibは次の3層で構成される
1.Scripting Layer
- pyplot
- df.plot()
2.Artist Layer
- ax = df.plot()
- グラフに表示されるものは全てArtist
3.Backend Layer
- backend_bases
matplotlibの階層構造を簡潔に表した図。
この図から読み取れること
- FigureオブジェクトにAxesオブジェクトが属している
- AxesオブジェクトにはAxisオブジェクトが属している
参考
○棒グラフの例1. 重なりを透過した棒グラフ
# create a dataframe of the countries of interest (cof) df_cof = df_can.loc[['Greece', 'Albania', 'Bulgaria'], years] # transpose the dataframe df_cof = df_cof.transpose() # let's get the x-tick values count, bin_edges = np.histogram(df_cof, 15) # Un-stacked Histogram df_cof.plot(kind ='hist', figsize=(10, 6), bins=15, alpha=0.35, xticks=bin_edges, color=['coral', 'darkslateblue', 'mediumseagreen'] ) plt.title('Histogram of Immigration from Greece, Albania, and Bulgaria from 1980 - 2013') plt.ylabel('Number of Years') plt.xlabel('Number of Immigrants') plt.show()
出力
○棒グラフの例2. 棒グラフへ数値埋め込み
### type your answer here df_top15.plot(kind='barh',figsize=(12,12),color = 'steelblue') plt.xlabel('Number of Immigrants') plt.title('Top 15 Conuntries Contributing to the Immigration to Canada between 1980 - 2013') # annotate value labels to each country for index, value in enumerate(df_top15): label = format(int(value), ',') # format int with commas # place text at the end of bar (subtracting 47000 from x, and 0.1 from y to make it fit within the bar) plt.annotate(label, xy=(value - 47000, index - 0.10), color='white') plt.show()
出力
○Subplotsの基本形
典型的な記述方法は以下の通り。
fig = plt.figure() # create figure ax = fig.add_subplot(nrows, ncols, plot_number) # create subplots
○散布図と近似直線の可視化
x = df_tot['year'] # year on x-axis y = df_tot['total'] # total on y-axis fit = np.polyfit(x, y, deg=1) df_tot.plot(kind='scatter', x='year', y='total', figsize=(10, 6), color='darkblue') plt.title('Total Immigration to Canada from 1980 - 2013') plt.xlabel('Year') plt.ylabel('Number of Immigrants') # plot line of best fit plt.plot(x, fit[0] * x + fit[1], color='red') # recall that x is the Years plt.annotate('y={0:.0f} x + {1:.0f}'.format(fit[0], fit[1]), xy=(2000, 150000)) plt.show() # print out the line of best fit 'No. Immigrants = {0:.0f} * Year + {1:.0f}'.format(fit[0], fit[1])