如何在 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 数据集分别提供了巴黎、安特卫普和伦敦的测量站 FR04014BETR801London 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_col=0parse_dates=True 参数分别定义了结果 DataFrame 的第一个(第 0 个)列作为索引,并将列中的日期转换为 Timestamp 对象。

  • 我想要快速地目视检查数据。

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

    使用 DataFrame 时,pandas 默认会为包含数值数据的每个列创建一个折线图。

  • 我只想绘制数据表中来自巴黎的数据的列。

    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。

其中一个选项是 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 中绘图的完整概述可在可视化页面中找到。