如何在 pandas 中创建图表?

从 pandas 表格数据创建图表的流程概览
pandas 绘图流程概览(原文配图)。
import pandas as pd
import matplotlib.pyplot as plt

本教程使用的数据

空气质量数据

本教程使用由 OpenAQ 提供、通过 py-openaq 包获取的二氧化氮(NO2)空气质量数据。air_quality_no2.csv 数据集给出了巴黎、安特卫普和伦敦的 FR04014、BETR801 与 London Westminster 测量站的 NO2 数值。

查看原始数据。

air_quality = pd.read_csv("data/air_quality_no2.csv", index_col=0, parse_dates=True)
air_quality.head()

原文展示的输出:

                     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

快速目视检查数据

air_quality.plot()
plt.show()

plot() 在原文中返回 <Axes: xlabel='datetime'>。

三个测量站的 NO2 时间序列折线图
全部数值列的折线图(原文配图)。

对于 DataFrame,pandas 默认会为每个包含数值数据的列创建一条折线。

只绘制巴黎测量站的数据列

air_quality["station_paris"].plot()
plt.show()

plot() 在原文中返回 <Axes: xlabel='datetime'>。

巴黎测量站的 NO2 时间序列折线图
只选择巴黎列(原文配图)。

要绘制某一列,可以将选取数据子集教程中的选择方法与 plot() 方法结合使用。因此,plot() 同时适用于 Series 和 DataFrame。

目视比较伦敦与巴黎测得的 NO2 数值

air_quality.plot.scatter(x="station_london", y="station_paris", alpha=0.5)
plt.show()

原文返回 <Axes: xlabel='station_london', ylabel='station_paris'>。

横轴为伦敦、纵轴为巴黎 NO2 数值的散点图
伦敦与巴黎的散点图(原文配图)。

除了调用 plot 时默认使用的 line 图,还可以使用多种其他图形。下面用标准 Python 查看可用的绘图方法:

[
    method_name
    for method_name in dir(air_quality.plot)
    if not method_name.startswith("_")
]

原文展示的输出:

['area',
 'bar',
 'barh',
 'box',
 'density',
 'hexbin',
 'hist',
 'kde',
 'line',
 'pie',
 'scatter']

其中一个选项是 DataFrame.plot.box(),即箱线图。box 方法也可用于这份空气质量示例数据:

air_quality.plot.box()
plt.show()

原文返回 <Axes: >。

三个测量站 NO2 数值分布的箱线图
空气质量数据的箱线图(原文配图)。

要了解默认折线图之外的图形,参阅用户指南的支持的绘图样式部分。

为每一列分别创建子图

axs = air_quality.plot.area(figsize=(12, 4), subplots=True)
plt.show()
每个测量站分别显示的面积子图
每列一个子图(原文配图)。

绘图函数通过 subplots 参数支持为各个数据列分别创建子图。可以进一步了解 pandas 各绘图函数提供的内置选项。

更多格式设置选项见用户指南的图表格式设置部分。

进一步定制、扩展或保存图表

fig, axs = plt.subplots(figsize=(12, 4))
air_quality.plot.area(ax=axs)
axs.set_ylabel("NO$_2$ concentration")
fig.savefig("no2_concentrations.png")
plt.show()

原文中 plot.area() 返回 <Axes: xlabel='datetime'>;set_ylabel() 返回 Text(0, 0.5, 'NO$_2$ concentration')。

自定义纵轴标签并可保存的 NO2 面积图
结合 Matplotlib 设置标签并保存图表(原文配图)。

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 绘图功能的完整介绍见用户指南的可视化页面。

原文:pandas 文档贡献者,How do I create plots in pandas?。读取时页面标示 pandas 3.0.6。本版本为中文翻译,保留原文示例、输出与配图;示例输出来自原文。© 2026 pandas via NumFOCUS, Inc.。源项目采用 BSD 3-Clause License:

BSD 3-Clause License

Copyright (c) 2008-2011, AQR Capital Management, LLC, Lambda Foundry, Inc. and PyData Development Team
All rights reserved.

Copyright (c) 2011-2026, Open source contributors.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容