plotnine.mapping.stage

class 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.

Parameters
startexpression | array_like | scalar

Aesthetic expression using primary variables from the layer data.

after_statexpression

Aesthetic expression using variables calculated by the stat.

after_scaleexpression

Aesthetic expression using aesthetics of the layer.

Examples

[1]:
%load_ext autoreload
%autoreload 2
%aimport plotnine

import pandas as pd
import numpy as np

from plotnine import *

%matplotlib inline

stage

[2]:
df = pd.DataFrame({
    'var1': list('abbcccddddeeeee'),
    'cat': list('RSRSRSRRRSRSSRS')
})

(ggplot(df, aes('var1'))
 + geom_bar()
)
../_images/stage_2_0.png
[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')
)
../_images/stage_4_0.png
[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')
)
../_images/stage_6_0.png
[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')
)
../_images/stage_8_0.png
[5]:
<ggplot: (97654321012345679)>