brb
brb

Reputation: 1179

Colour bars based on values in pandas dataframe when using plotnine

I am trying to build a waterfall chart using plotnine. I would like to colour the starting and ending bars as grey (ideally I want to specify hexadecimal colours), increases as green and decreases as red.

Below is some sample data and my current plot. I am trying to set fill to the pandas column colour, but the bars are all black. I have also tied putting fill in the geom_segment, but this does not work either.

df = pd.DataFrame({})
df['label'] = ('A','B','C','D','E')
df['percentile'] = (10)*5
df['value'] = (100,80,90,110,110)
df['yStart'] = (0,100,80,90,0)
df['barLabel'] = ('100','-20','+10','+20','110')
df['labelPosition'] = ('105','75','95','115','115')
df['colour'] = ('grey','red','green','green','grey')

p = (ggplot(df, aes(x=np.arange(0,5,1), xend=np.arange(0,5,1), y='yStart',yend='value',fill='colour'))
    + theme_light(6)
    + geom_segment(size=10)
    + ylab('value')
    + scale_y_continuous(breaks=np.arange(0,141,20), limits=[0,140], expand=(0,0))
)

enter image description here

EDIT

Based on teunbrand's comment of changing fill to color, I have the following. How do I specify the actual colour, preferably in hexadecimal format?

enter image description here

Upvotes: 0

Views: 725

Answers (1)

brb
brb

Reputation: 1179

Just to close this question off, credit goes to teunbrand in the comments for the solution.

geom_segment() has a colour aesthetic but not a fill aesthetic. Replace fill='colour' with colour='colour'.

Plotnine will use default colours for the bars. Use scale_color_identity() if the contents of the DataFrame column are literal colours, or scale_colour_manual() to manually specify a tuple or list of colours. Both forms accept hexadecimal colours.

Upvotes: 1

Related Questions