plotnine: Python版的ggplot2作图库
同样的基本作图任务,plotnine比matplotlib和seaborn代码量少,更美观。所以我又重新发一遍,大家可以先收藏起来,后面总有用到的时候~R语言的ggplot2绘图能力超强,python虽有matplotlib,但是语法臃肿,使用复杂,入门极难,seaborn的出现稍微改善了matplotlib代码量问题,但是定制化程度依然需要借助matplotlib,使用难度依然很大。而且咱们经管专业学编程语言,一直有一个经久不衰的问题-“学数据分析,到底选择R还是Python”。通过plotnine这个库,你就可以在python世界中体验下R语言的新奇感,体验可视化之美,如果着迷上瘾,再学R也不迟。plotnine包,可以实现绝大多数ggplot2的绘图功能,两者语法十分相似,R和Python的语法转换成本大大降低。plotnine文档 https://plotnine.readthedocs.io/en/latest/R语言ggplot2文档 https://ggplot2.tidyverse.org/reference/index.html安装pip install plotnine准备数据from plotnine.data import mpg#dataframempg.head()manufacturermodeldisplyearcyltransdrvctyhwyflclass0audia41.819994auto(l5)f1829pcompact1audia41.819994manual(m5)f2129pcompact2audia42.020084manual(m6)f2031pcompact3audia42.020084auto(av)f2130pcompact4audia42.819996auto(l5)f1626pcompact快速作图qplot我们先直接看最简单好用的快速作图函数qplot(x, y, data)横坐标displ纵坐标cty数据mpgfrom plotnine import qplotqplot(x='displ',y='cty',data=mpg)
![](http://n4.ikafan.com/assetsj/blank.gif)
<ggplot: (322851325)>ggplot图层qplot是快速作图函数,如果想让图更好看,进行私人订制,那么我们需要进行图层设计首先设置ggplot图层(相当于买了一个高级画布),数据mpg横坐标x轴为displ纵坐标y轴cty在plotnine中,变量所对应的数据均可通过字段名调用from plotnine import ggplot, geom_point, aesggplot(aes(x='displ', y='cty'), mpg)
![](http://n4.ikafan.com/assetsj/blank.gif)
<ggplot: (321957793)>图层叠加我们可以看到,已经绘制出一个空的ggplot图层,x轴为displ,y轴为cty。接下来我们给这个图层上加上数据对应的散点,使用geom_point()直接追加在ggplot图层之上即可。(ggplot(aes(x='displ', y='cty'), mpg)+ geom_point())
![](http://n4.ikafan.com/assetsj/blank.gif)
<ggplot: (322466061)>color在上图中,散点是没有区分每辆车的气缸数cyl。在geom_point()中,我们可以按照气缸数cyl分门别类,按照颜色显示出来(ggplot(aes(x='displ', y='cty'), mpg)+ geom_point(aes(color='cyl')))
![](http://n4.ikafan.com/assetsj/blank.gif)
<ggplot: (323647173)>上图挺好看的,有时候需要绘制的字段是离散型数值,但是上色后可能不够明显,需要声明该字段为离散型。这时候用factor()来告诉plotnine,这个字段是离散型数值(ggplot(aes(x='displ', y='cty'), mpg)+ geom_point(aes(color='factor(cyl)')))
![](http://n4.ikafan.com/assetsj/blank.gif)
<ggplot: (321918425)>size有时候为了增加可视化显示的维度数,还可以考虑加入点的大小size(ggplot(aes(x='displ', y='cty'), mpg)+ geom_point(aes(size='hwy')))
![](http://n4.ikafan.com/assetsj/blank.gif)
<ggplot: (323399013)>梯度色如果你想自己设置颜色的梯度,可以通过scale_color_gradient设置from plotnine import scale_color_gradient(ggplot(aes(x='displ', y='cty'), mpg)+ geom_point(aes(color='hwy'))+ scale_color_gradient(low='blue', high='red'))
![](http://n4.ikafan.com/assetsj/blank.gif)
<ggplot: (323622897)>条形图plotnine中可绘制的图有很多,刚刚已经讲了散点图,接下来我们看看plotnine中的条形图。首先准备一下数据import pandas as pddf = pd.DataFrame({'variable': ['gender', 'gender', 'age', 'age', 'age', 'income', 'income', 'income', 'income'],'category': ['Female', 'Male', '1-24', '25-54', '55+', 'Lo', 'Lo-Med', 'Med', 'High'],'value': [60, 40, 50, 30, 20, 10, 25, 25, 40],})df['variable'] = pd.Categorical(df['variable'], categories=['gender', 'age', 'income'])df['category'] = pd.Categorical(df['category'], categories=df['category'])dfvariablecategoryvalue0genderFemale601genderMale402age1-24503age25-54304age55+205incomeLo106incomeLo-Med257incomeMed258incomeHigh40from plotnine import ggplot, aes, geom_text, position_dodge, geom_point#调整文本位置dodge_text = position_dodge(width=0.9) # new(ggplot(df, aes(x='variable',y='value',fill='category')) #类别填充颜色+ geom_col(position='dodge',show_legend=False) # modified+ geom_text(aes(y=-.5, label='category'), # newposition=dodge_text,color='gray', #文本颜色size=8, #字号angle=30, #文本的角度va='top')+ lims(y=(-5, 60)) # new)
![](http://n4.ikafan.com/assetsj/blank.gif)
<ggplot: (334727813)>from plotnine.data import economics_longeconomics_long.head()datevariablevaluevalue0101967-07-01pce507.40.00000011967-08-01pce510.50.00026621967-09-01pce516.30.00076431967-10-01pce512.90.00047241967-11-01pce518.10.000918from plotnine import ggplot, aes, geom_line(ggplot(economics_long, aes(x='date', y='value01', color='variable'))+ geom_line())
![](http://n4.ikafan.com/assetsj/blank.gif)
<ggplot: (334895445)>plotnine目前已经支持绝大多数ggplot2,但是文档方面没有ggplot2全,所以学习plotnine时可以参考ggplot2。plotnine文档 https://plotnine.readthedocs.io/en/latest/R语言ggplot2文档 https://ggplot2.tidyverse.org/reference/index.html