天天看點

python 畫圖_傳說中的畫圖神器Plotnine,Python中的ggplot2​前言Plotnine圖形建立

​前言

Python的繪圖庫(如matplotlib和seaborn)也允許使用者建立優雅的圖形,但是與R中的ggplot2的簡單、可讀和層次方法相比,它缺乏實作圖形文法的标準化文法,這使得用Python實作它更加困難。。

python 畫圖_傳說中的畫圖神器Plotnine,Python中的ggplot2​前言Plotnine圖形建立

Plotnine

R的忠實使用者知道,ggplot2可以使您在處理探索性資料分析和資料可視化時更加簡單。它使得建立優雅而強大的情節變得如此容易,進而有助于解讀資料中的潛在關系。

那麼Python使用者是否也有類似的畫圖工具呢?

這個問題的答案在Plotnine中。

Plotnine的風格與R中的ggplot2有99%的相似之處,主要差別在于括号的使用,您将在下面的幾個簡短示例中看到。使用plotnine的一個最好的收獲是,輸出基本上與在R中得到的相同。在視覺上沒有顯著的差別。

接下來我們簡要介紹如何使用Plotnine。

安裝:

pip install pandas plotnine           

讓我們用必要的庫來設定工作環境,并将csv檔案加載到名為survs_df的資料架構中:

ggplot(survs_df, aes(x='weight', y='hindfoot_length',    size = 'year')) + geom_point()           

要使用plotnine中的ggplot類生成一個圖形,我們必須提供三件事:

  • 包含我們的資料的資料框。
  • 如何将資料架構的列轉換為圖形元素的位置、顔色、大小和形狀(“美學”)。
  • 要顯示的實際圖形元素(“幾何對象”)
ggplot(survs_df, aes(x='weight', y='hindfoot_length')) + geom_point()           
python 畫圖_傳說中的畫圖神器Plotnine,Python中的ggplot2​前言Plotnine圖形建立

圖形建立

對于plotnine中的API,我們可以使用許多選項來建立圖形。

(ggplot(mtcars, aes(‘wt’, ‘mpg’, color=’factor(cyl)’))+ geom_point()+ labs(title=’Miles per gallon vs Weight’, x=’Weight’, y=’Miles per gallon’)+ guides(color=guide_legend(title=’Number of Cylinders’)) )           
python 畫圖_傳說中的畫圖神器Plotnine,Python中的ggplot2​前言Plotnine圖形建立

R中的ggplot的主要賣點之一是FACET的能力。對于用一行代碼繪制資料子集,我們也有許多選項:

(ggplot(mtcars, aes(‘wt’, ‘mpg’, color=’factor(cyl)’))+ geom_point()+ labs(title=’Miles per gallon vs Weight’,x=’Weight’, y=’Miles per gallon’)+ guides(color=guide_legend(title=’Cylinders’))+ facet_wrap(‘~gear’))           
python 畫圖_傳說中的畫圖神器Plotnine,Python中的ggplot2​前言Plotnine圖形建立

隻需在前面代碼的末尾添加facet_wrap(' ~gear '),我們現在就有了一個分面情節。這實際上比使用Matplotlib和Seaborn要簡單得多。

​參考文章:

https://www.kdnuggets.com/2019/12/python-alternative-ggplot2.html

https://monashdatafluency.github.io/python-workshop-base/modules/plotting_with_ggplot/

繼續閱讀