Comprehensive Guide to Plotnine: Installation, Data, Aesthetics, Geoms, Stats, Scales, Positions, Coordinates, Facets, and Themes
This article provides a detailed tutorial on plotnine, the Python implementation of the Grammar of Graphics, covering installation methods, data handling, aesthetic mappings, geometric objects, statistical transformations, scales, position adjustments, coordinate systems, faceting, themes, and multi‑panel plotting with code examples.
plotnine is the Python implementation of the Grammar of Graphics, offering functionality almost identical to ggplot2 for creating layered graphics.
Installation
Using pip (with Tsinghua mirror for speed):
#指定清华源快速安装plotnine
pip install plotnine -i https://pypi.tuna.tsinghua.edu.cn/simpleUsing conda:
conda install plotnineUsing git on Linux:
git clone https://github.com/has2k1/plotnine.git
cd plotnine
pip install -e .Data (datasets)
plotnine provides several built‑in datasets accessible via plotnine.data . Example to list them:
#内置数据集
print(dir(plotnine.data))'diamonds', 'economics', 'economics_long', 'faithful', 'faithfuld', 'huron', 'luv_colours', 'meat', 'midwest', 'mpg', 'msleep', 'mtcars', 'pageviews', 'presidential', 'seals', 'txhousing'
Aesthetic Attributes
Map data columns to visual properties using aes . Example mapping displacement and highway mileage with colour by class:
#aes中设置点的属性,按class使用不同颜色
ggplot(mpg, aes('displ', 'hwy', colour = 'class')) + geom_point()Geometric Objects (Geoms)
All geoms start with geom_ . Example listing available geoms and creating a boxplot:
print(len([i for i in dir(plotnine.geoms) if i.startswith('geom_')]))
print([i for i in dir(plotnine.geoms) if i.startswith('geom_')])
#geom_boxplot()绘制箱图
ggplot(mpg, aes('class', 'hwy')) + geom_boxplot()Statistical Transformations (Stats)
Stats start with stat_ . Example listing them and summarising mean values:
print([i for i in dir(plotnine.stats) if i.startswith('stat_')])
#统计每组数据均值,红点表示
ggplot(mpg, aes('trans', 'cty')) + geom_boxplot() +
stat_summary(mapping=None, data=None, geom='point',
fun_data='mean_cl_boot', colour='red', size=4) +
theme(axis_text_x = element_text(angle=90, hjust=1))Scales
Scales map data values to visual channels. Example using shape and size aesthetics with custom scales:
#点按f1使用不同marker,按cty使用不同siz
ggplot(mpg, aes('displ', 'hwy', colour='class')) +
geom_point(aes(shape='fl', size='cty')) +
scale_shape() + scale_size()Position Adjustments
Control how geometries are positioned. Examples of stacked, filled, and dodged bar plots:
print(ggplot(mpg, aes('cty', fill='class')) + geom_bar())
print(ggplot(mpg, aes('cty', fill='class')) + geom_bar(position = "fill"))
print(ggplot(mpg, aes('cty', fill='class')) + geom_bar(position = "dodge"))Coordinate Systems
Available coordinate systems include coord_cartesian , coord_flip , etc. Example listing them:
print([i for i in dir(plotnine.coords) if i.startswith('coord_')])Faceting
Facets split data into multiple panels. Example using facet_wrap and facet_grid :
#facet_wrap
(ggplot(mpg, aes(x='displ', y='hwy')) + geom_point() + facet_wrap('class') + labs(x='displacement', y='horsepower'))
#facet_grid
(ggplot(mpg, aes(x='displ', y='hwy')) + geom_point() + facet_grid('drv ~ .', labeller = 'label_both') + labs(x='displacement', y='horsepower'))Themes and Sub‑Plotting
Various themes are available (e.g., theme_xkcd , theme_dark ). Example creating four sub‑plots with different themes and coordinates:
from matplotlib import gridspec
p1 = ggplot(mpg, aes('displ', 'hwy')) + geom_point() + geom_smooth() + theme_xkcd()
p2 = ggplot(mpg, aes('displ', 'hwy')) + geom_point() + geom_smooth() + coord_cartesian(xlim=(5,7)) + theme_dark()
p3 = ggplot(mpg, aes('cty', 'displ')) + geom_point() + geom_smooth() + theme_matplotlib()
p4 = ggplot(mpg, aes('displ', 'cty')) + geom_point() + geom_smooth() + coord_fixed() + theme_linedraw()
fig = (ggplot()+geom_blank(data=mpg)+theme_void()).draw()
gs = gridspec.GridSpec(2,2)
ax1 = fig.add_subplot(gs[0,0])
ax2 = fig.add_subplot(gs[0,1])
ax3 = fig.add_subplot(gs[1,0])
ax4 = fig.add_subplot(gs[1,1])
_ = p1._draw_using_figure(fig,[ax1])
_ = p2._draw_using_figure(fig,[ax2])
_ = p3._draw_using_figure(fig,[ax3])
_ = p4._draw_using_figure(fig,[ax4])
plt.tight_layout()
plt.show()Reference: plotnine documentation
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.