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'>。

对于 DataFrame,pandas 默认会为每个包含数值数据的列创建一条折线。
只绘制巴黎测量站的数据列
air_quality["station_paris"].plot()
plt.show()
plot() 在原文中返回 <Axes: xlabel='datetime'>。

要绘制某一列,可以将选取数据子集教程中的选择方法与 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'>。

除了调用 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: >。

要了解默认折线图之外的图形,参阅用户指南的支持的绘图样式部分。
为每一列分别创建子图
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')。

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











暂无评论内容