如何在 pandas 中建立繪圖?#
In [1]: import pandas as pd
In [2]: import matplotlib.pyplot as plt
- 空氣品質資料
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
和parse_dates
參數的使用方式,分別將第一個 (第 0 個) 欄定義為結果DataFrame
的索引,並將該欄中的日期轉換為Timestamp
物件。
我想快速查看資料。
In [5]: air_quality.plot() Out[5]: <Axes: xlabel='datetime'> In [6]: plt.show()
使用
DataFrame
時,pandas 會預設為每個具有數字資料的欄位建立一個折線圖。
我只想繪製資料表中巴黎資料的欄位。
In [7]: air_quality["station_paris"].plot() Out[7]: <Axes: xlabel='datetime'> In [8]: plt.show()
若要繪製特定欄位,請使用 子集資料教學課程 的選取方法,搭配
plot()
方法。因此,plot()
方法可以在Series
和DataFrame
上執行。
我想視覺化比較倫敦與巴黎測量到的 \(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()
除了使用 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()

如需預設折線圖以外的繪圖簡介,請參閱使用者指南關於 支援的繪圖樣式 的章節。
我希望每個欄位都在一個獨立的子繪圖中。
In [14]: axs = air_quality.plot.area(figsize=(12, 4), subplots=True) In [15]: plt.show()
每個資料欄位的獨立子繪圖由
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()
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 和 DataFrames。預設情況下,每個欄位都繪製成不同的元素(線條、箱型圖,…)。
pandas 建立的任何繪圖都是 Matplotlib 物件。
pandas 中繪圖的完整概述在 視覺化頁面 中提供。