Pandas萬花筒:讓繪圖變得更美觀
本文轉(zhuǎn)載自公眾號“讀芯術(shù)”(ID:AI_Discovery)。
流行 Python 數(shù)據(jù)分析庫 Pandas 中的繪圖功能一直是迅速繪制圖表的首選之一。但是,其可用的可視化效果總是十分粗略,實用有余、美觀不足。
筆者常用 Pandas 的繪圖功能快速地執(zhí)行一些可視的數(shù)據(jù)探索,但在介紹數(shù)據(jù)洞察時,我會使用“更美觀”的繪圖庫(如 Plotly 或 Bokeh )來重做可視化。
自最新的 Pandas 版本0.25.3發(fā)布后,無需這樣做了,現(xiàn)在我們可以使用第三方可視化庫作為 Pandas 繪圖功能的后端。Plotly是一款基于 web 實現(xiàn)交互式可視化的流行Python庫,其最近發(fā)布了 Pandas繪圖后端。
來看看如何使用 Plotly 和 Bokeh 后端創(chuàng)建更豐富的可視化效果。
使用不同的后端
想要激活繪圖功能的不同后端需在導(dǎo)入 pandas 后,添加此行代碼:
- pd.options.plotting.backend = 'plotly'
當(dāng)前可用的后端有:
- Plotly
- Holoviews
- Matplotlib
- Pandas _bokeh
- Hyplot
Plotly后端
Plotly是一個 Python庫,其支持豐富的交互式可視化效果。Plotly包的好處之一在于它是在庫的 Javascript 版本之上構(gòu)建的,這意味著圖表會基于Web,可以顯示為 HTML 文件或嵌入到基于Python的Web應(yīng)用程序中。用戶還可以將可視化內(nèi)容下載為高質(zhì)量的圖像文件,以便在文檔或論文中使用。
下面來瀏覽一些Plotly作為Pandas繪圖后端的快速示例。
如果還沒有安裝Plotly ,則需要使用pip intsall plotly來安裝。如果是在Jupyterlab中使用 Plotly ,則需要額外執(zhí)行幾個安裝步驟來顯示可視化效果。首先,安裝IPywaidgets:
- pipenv install jupyterlab " ipywidgets>=7.5"
- pip install jupyterlab "ipywidgets>=7.5"
然后運行以下命令以安裝Plotly擴展:
- jupyter labextension install jupyterlab-plotly@4.8.1
為了說明繪圖后端的用法,使用openml.org名為“wine(葡萄酒)”的數(shù)據(jù)集。
- import pandas as pd
- import numpy as np
- from sklearn.datasets import fetch_openml
- pd.options.plotting.backend ='plotly'
- X,y =fetch_openml("wine", version=1, as_frame=True, return_X_y=True)
- data = pd.concat([X,y], axis=1)
- data.head()
該數(shù)據(jù)集由各類葡萄酒的多個特征和相應(yīng)的標(biāo)簽組成。下圖顯示了數(shù)據(jù)集的前幾行。
繪圖功能的工作方式與標(biāo)準(zhǔn)Pandas繪圖功能的工作方式大致相同,只是現(xiàn)在可視化效果同Plotly一樣豐富。下面的代碼繪制了數(shù)據(jù)集中兩個特征之間的關(guān)系。
- fig = data[['Alcohol', 'Proline']].plot.scatter(y='Alcohol', x='Proline')
- fig.show()
可以通過組合 Pandas 的groupby函數(shù)創(chuàng)建一個柱狀圖來總結(jié)類之間的平均色調(diào)差異:
- data[['Hue','class']].groupby(['class']).mean().plot.bar()
將類添加到之前創(chuàng)建的散點圖中。使用Plotly,可以輕松地給每個類使用不同的顏色,以便直觀地區(qū)分:
- fig = data[['Alcohol', 'Proline']].plot.scatter(y='Alcohol', x='Proline')
- fig.show()
Bokeh 后端
Bokeh 也可以提供豐富交互式可視化效果。其可視化圖表可以在 Web 瀏覽器中查看,嵌入到 Web應(yīng)用程序中或用于創(chuàng)建交互式儀表板。Bokeh 甚至有一個流式 API,可以為流數(shù)據(jù)(如金融市場數(shù)據(jù))創(chuàng)建實時可視化圖表。
庫可以通過pip來安裝:
- pip install pandas-bokeh
要在 Jupyterlab中顯示 Bokeh的可視化效果,需要安裝兩個新的擴展:
- jupyter labextension install @jupyter-widgets/jupyterlab-managerjupyterlabextension install @bokeh/jupyter_bokeh
使用 Bokeh 后端重新創(chuàng)建之前的散點圖:
- pd.options.plotting.backend ='pandas_bokeh'
- import pandas_bokeh
- from bokeh.io import output_notebook
- from bokeh.plotting import figure, show
- output_notebook()
- p1= data.plot_bokeh.scatter(x='Hue',
- y='Proline',
- category='class',
- title='Proline and Hue by wine class',
- show_figure=False)
- show(p1)
可視化效果如下:
Bokeh 有一個plot_grid函數(shù),可為多個圖表創(chuàng)建儀表板式布局。下面的代碼在網(wǎng)格布局中創(chuàng)建四個圖表:
- output_notebook()
- p1 = data.plot_bokeh.scatter(x='Hue',
- y='Proline',
- category='class',
- title='Proline and Hue by wine class',
- show_figure=False)
- p2 = data[['Hue','class']].groupby(['class']).mean().plot.bar(title='Mean Hue per Class')
- df_hue = pd.DataFrame({
- 'class_1': data[data['class'] =='1']['Hue'],
- 'class_2': data[data['class'] =='2']['Hue'],
- 'class_3': data[data['class'] =='3']['Hue']},
- columns=['class_1', 'class_2', 'class_3'])
- p3 = df_hue.plot_bokeh.hist(title='Distribution perClass: Hue')
- df_proline = pd.DataFrame({
- 'class_1': data[data['class'] =='1']['Proline'],
- 'class_2': data[data['class'] =='2']['Proline'],
- 'class_3': data[data['class'] =='3']['Proline']},
- columns=['class_1', 'class_2', 'class_3'])
- p4 =df_proline.plot_bokeh.hist(title='Distribution per Class: Proline')
- pandas_bokeh.plot_grid([[p1, p2],
- [p3, p4]], plot_width=450)
為內(nèi)置的Pandas繪圖功能添加多個第三方后端,這大大增強了該庫用于數(shù)據(jù)可視化的能力。從此之后,pandas就可以集美貌與實用于一身啦。