如果您不熟悉图形的语法,这里有一个快速概述:
如您所见,从您的数据开始,有几个组件构成了图形的语法。在确定要可视化的数据后,您必须指定您感兴趣的变量。例如,您可能希望在 x 轴上显示一个变量,在 y 轴上显示另一个变量。第三,你必须定义你想使用什么类型的几何对象(geometric object,简称 geom)。这可以是从条形图到散点图或任何其他现有绘图类型的任何东西。
importpandasaspdimportnumpyasnpfrompandas.api.typesimportCategoricalDtypefromplotnineimport*fromplotnine.dataimportmpg%matplotlibinline(ggplot(mpg)# defining what data to use+aes(x='class')# defining what variable to use+geom_bar(size=20)# defining the type of plot to use)
(ggplot(mpg)+aes(x='class')+geom_bar(size=20)+coord_flip()# flipping the x- and y-axes+labs(title='Number of Vehicles per Class',x='Vehicle Class',y='Number of Vehicles')# customizing labels)
(ggplot(mpg)+aes(x='displ',y='hwy',color='class')+geom_point()+labs(title='Engine Displacement vs. Highway Miles per Gallon',x='Engine Displacement, in Litres',y='Highway Miles per Gallon'))
将 color 添加到 aesthetics 组件中将会促使 plotnine 呈现一个在 x 轴上使用 displ(发动机排量,以升为单位)和在 y 轴上使用 hwy(每加仑高速公路英里数),并根据 class 变量为数据着色的二维图。我们还可以将几何对象切换到 geom_point(),这将为我们提供散点图而不是条形图。 让我们来看看会是什么样子: