
pandasでdf.plot()をすると、matplotlibを使わなくても簡単にグラフを作ることが出来る。
しかし、複数のグラフを作りたくてsubplotsしようとすると途端に面倒になり、df.plot()の引数やmatplotlibのfigureをあれこれする必要が出てくる。
matplotlibにはgca()というget current axesなる便利メソッドがあるので、gcaをpandas.plot()の引数に渡し、subplotのループを回せば、対象となるaxesを自動で認識して複数のグラフを簡単に作ることが出来た。
例えば2x2のグラフを作りたい時はこのような感じ。
plt.figure(figsize=(10,10))
count=0
for _ in range(1,5):
count+=1
plt.subplot(2,2,count)
df[target_col].plot(ax=plt.gca())参考
pandas.DataFrame.plot — pandas 3.0.5 documentation
matplotlib.pyplot.subplot — Matplotlib 3.5.0 documentation

Matplotlib gca(): Get the Current Axes
Understand matplotlib.pyplot.gca(), current Axes state, gca() versus gcf(), and why explicit subplots are clearer in new...

How to plot multiple dataframes in subplots
I have a few Pandas DataFrames sharing the same value scale, but having different columns and indices. When invoking df....


コメント