pandasでプロットを作成するには?#

../../_images/04_plot_overview.svg
In [1]: import pandas as pd

In [2]: import matplotlib.pyplot as plt
このチュートリアルで使用されるデータ
  • OpenAQが提供し、py-openaqパッケージを使用した、\(NO_2\)に関する大気質データを使用します。air_quality_no2.csvデータセットは、それぞれパリ、アントワープ、ロンドンの測定ステーション *FR04014*、*BETR801*、*London Westminster* の\(NO_2\)値を提供します。

    生データへ
    In [3]: air_quality = pd.read_csv("data/air_quality_no2.csv", index_col=0, parse_dates=True)
    
    In [4]: air_quality.head()
    Out[4]: 
                         station_antwerp  station_paris  station_london
    datetime                                                           
    2019-05-07 02:00:00              NaN            NaN            23.0
    2019-05-07 03:00:00             50.5           25.0            19.0
    2019-05-07 04:00:00             45.0           27.7            19.0
    2019-05-07 05:00:00              NaN           50.4            16.0
    2019-05-07 06:00:00              NaN           61.9             NaN
    

    注記

    read_csv関数のindex_colparse_datesパラメータを使用して、最初の(0番目の)列を結果のDataFrameのインデックスとして定義し、列の日付をTimestampオブジェクトに変換する方法について説明します。

  • データを視覚的に素早く確認したい。

    In [5]: air_quality.plot()
    Out[5]: <Axes: xlabel='datetime'>
    
    In [6]: plt.show()
    
    ../../_images/04_airqual_quick.png

    DataFrameを使用すると、pandasはデフォルトで数値データを持つ各列に対して1つの折れ線グラフを作成します。

  • パリのデータを含むデータテーブルの列のみをプロットしたい。

    In [7]: air_quality["station_paris"].plot()
    Out[7]: <Axes: xlabel='datetime'>
    
    In [8]: plt.show()
    
    ../../_images/04_airqual_paris.png

    特定の列をプロットするには、データサブセットチュートリアルの選択方法とplot()メソッドを組み合わせて使用します。したがって、plot()メソッドはSeriesDataFrameの両方で機能します。

  • ロンドンとパリで測定された\(NO_2\)値を視覚的に比較したい。

    In [9]: air_quality.plot.scatter(x="station_london", y="station_paris", alpha=0.5)
    Out[9]: <Axes: xlabel='station_london', ylabel='station_paris'>
    
    In [10]: plt.show()
    
    ../../_images/04_airqual_scatter.png

plot関数を使用する場合のデフォルトのlineプロット以外にも、データをプロットするための多くの代替手段があります。利用可能なプロット方法の概要を把握するために、標準的なPythonを使用してみましょう。

In [11]: [
   ....:     method_name
   ....:     for method_name in dir(air_quality.plot)
   ....:     if not method_name.startswith("_")
   ....: ]
   ....: 
Out[11]: 
['area',
 'bar',
 'barh',
 'box',
 'density',
 'hexbin',
 'hist',
 'kde',
 'line',
 'pie',
 'scatter']

注記

多くの開発環境、IPython、Jupyter Notebookでは、TABボタンを使用して利用可能なメソッドの概要を確認できます。たとえば、air_quality.plot. + TAB。

オプションの1つにDataFrame.plot.box()があり、これはボックスプロットを参照しています。boxメソッドは大気質のサンプルデータに適用できます。

In [12]: air_quality.plot.box()
Out[12]: <Axes: >

In [13]: plt.show()
../../_images/04_airqual_boxplot.png
ユーザーガイドへ

デフォルトの折れ線グラフ以外のプロットの概要については、サポートされているプロットスタイルに関するユーザーガイドセクションを参照してください。

  • 各列を別々のサブプロットに表示したい。

    In [14]: axs = air_quality.plot.area(figsize=(12, 4), subplots=True)
    
    In [15]: plt.show()
    
    ../../_images/04_airqual_area_subplot.png

    plot関数のsubplots引数によって、各データ列の別々のサブプロットがサポートされています。各pandasプロット関数で利用可能な組み込みオプションを確認することをお勧めします。

ユーザーガイドへ

その他の書式設定オプションについては、プロットの書式設定に関するユーザーガイドセクションを参照してください。

  • 結果のプロットをさらにカスタマイズ、拡張、または保存したい。

    In [16]: fig, axs = plt.subplots(figsize=(12, 4))
    
    In [17]: air_quality.plot.area(ax=axs)
    Out[17]: <Axes: xlabel='datetime'>
    
    In [18]: axs.set_ylabel("NO$_2$ concentration")
    Out[18]: Text(0, 0.5, 'NO$_2$ concentration')
    
    In [19]: fig.savefig("no2_concentrations.png")
    
    In [20]: plt.show()
    
    ../../_images/04_airqual_customized.png

pandasによって作成された各プロットオブジェクトはMatplotlibオブジェクトです。Matplotlibはプロットをカスタマイズするための多くのオプションを提供するため、pandasとMatplotlib間のリンクを明示的にすることで、Matplotlibのすべての機能をプロットに利用できます。この戦略は前の例で使用されています。

fig, axs = plt.subplots(figsize=(12, 4))        # Create an empty Matplotlib Figure and Axes
air_quality.plot.area(ax=axs)                   # Use pandas to put the area plot on the prepared Figure/Axes
axs.set_ylabel("NO$_2$ concentration")          # Do any Matplotlib customization you like
fig.savefig("no2_concentrations.png")           # Save the Figure/Axes using the existing Matplotlib method.
plt.show()                                      # Display the plot

覚えておくこと

  • .plot.*メソッドは、SeriesとDataFrameの両方で適用できます。

  • デフォルトでは、各列は異なる要素(折れ線グラフ、ボックスプロットなど)としてプロットされます。

  • pandasによって作成されたすべてのプロットはMatplotlibオブジェクトです。

ユーザーガイドへ

pandasでのプロットの完全な概要は、視覚化ページで提供されています。