在 Plotnine 官方网站中,提供了一些比较经典的案例,如果能够将这些案例分析清楚,对提高 Plotnine 的应用技能大有裨益。本课就选择两个案例抛砖引玉,供参考。
3.3.1 柱形图及坐标轴设置
本案例是关于柱形图和对其坐标轴设置,案例中核心类为 plotnine.geoms.geom_col(点击这里详见官方地址)。
还是先创建数据集:
import pandas as pd
import numpy as np
from plotnine import *
df = 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
variable | category | value | |
---|---|---|---|
0 | gender | Female | 60 |
1 | gender | Male | 40 |
2 | age | 1-24 | 50 |
3 | age | 25-54 | 30 |
4 | age | 55+ | 20 |
5 | income | Lo | 10 |
6 | income | Lo-Med | 25 |
7 | income | Med | 25 |
8 | income | High | 40 |
然后绘制柱形图:
(ggplot(df, aes(x='variable', y='value', fill='category'))
+ geom_col()
)
代码比较简单,但是因为特征 variable 的每个值所对应的 value 特征值自动成为一个柱子,而该柱子又是根据 fill='category' 填充(即柱子本身根据特征 category 的值划分为若干部分),图显得有点乱,不如绘制簇状柱形图清晰。
(ggplot(df, aes(x='variable', y='value', fill='category'))
+ geom_col(stat='identity', position='dodge') #①
)
① 增加了两个参数,就改为簇状柱形图了。
- stat:默认为 'identity',表示对本图层数据进行统计变换。当然,这不是出现“簇”的决定参数。
- position:默认为 'stack',表示堆叠的柱形图。如果设置为 'dodge',就出现簇了。
旁边虽然有图例,可以对应看到每种颜色的柱状图所表示的 category 值,但是,不如直接在柱形图上标示更清晰。为此可以进行如下修改:
dodge_text = position_dodge(width=0.9) # ②
(ggplot(df, aes(x='variable', y='value', fill='category'))
+ geom_bar(stat='identity', position='dodge', show_legend=False) # ③
+ geom_text(aes(y=-.5, label='category'), # ④
position=dodge_text,
color='gray', size=8, angle=45, va='top')
+ lims(y=(-5, 60)) # ⑤
)
输出结果:
网友评论