plotnine.mapping.stage(start=None, after_stat=None, after_scale=None)[source]¶Stage allows you evaluating mapping at more than one stage
You can evaluate an expression of a variable in a dataframe, and later evaluate an expression that modifies the values mapped to the scale.
Aesthetic expression using primary variables from the layer data.
Aesthetic expression using variables calculated by the stat.
Aesthetic expression using aesthetics of the layer.
[1]:
%load_ext autoreload
%autoreload 2
%aimport plotnine
import pandas as pd
import numpy as np
from plotnine import *
%matplotlib inline
[2]:
df = pd.DataFrame({
'var1': list('abbcccddddeeeee'),
'cat': list('RSRSRSRRRSRSSRS')
})
(ggplot(df, aes('var1'))
+ geom_bar()
)
[2]:
<ggplot: (97654321012345679)>
Add the corresponding count on top of each bar.
[3]:
(ggplot(df, aes('var1'))
+ geom_bar()
+ geom_text(aes(label=after_stat('count')), stat='count')
)
[3]:
<ggplot: (97654321012345679)>
Adjust the y position so that the counts do not overlap the bars.
[4]:
(ggplot(df, aes('var1'))
+ geom_bar()
+ geom_text(aes(label=after_stat('count'), y=stage(after_stat='count', after_scale='y+.1')), stat='count')
)
[4]:
<ggplot: (97654321012345679)>
Note that this will work even nicely for stacked bars where adjustig the position with nudge_y=0.1 would not.
[5]:
(ggplot(df, aes('var1', fill='cat'))
+ geom_bar()
+ geom_text(aes(label=after_stat('count'), y=stage(after_stat='count', after_scale='y+.1')), stat='count', position='stack')
)
[5]:
<ggplot: (97654321012345679)>