plotnine, keep same position of geom_bar(position='dodge') when value is missing

963 Views Asked by At

This minimal code

import pandas as pd
import plotnine as p9

df = pd.DataFrame({
    'variable': ['a', 'b', 'b'],
    'value': [1, 1, 1],
    'name': ['one', 'one', 'two']
})
(
    p9.ggplot(df, p9.aes(x='name', y='value', fill='variable'))
    + p9.geom_bar(stat='identity', position=p9.position_dodge(preserve='single'))
)

produces the following incorrect bar plot, due to a missing value. bar plot with incorrect bar placement

How can I get the bar for name two and variable b to be at the correct position (at right of the two x-axis tick)? Visualization of what I want

1

There are 1 best solutions below

0
On

Plotnine does not preserve any spaces for empty categories of a bar plot. But, you can get better positioning with position_dodge2(preserve='single') which gives centered the bars for every x position.