Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the y axis to display percent (%) in Python Plotnine barplot?

How can we change y axis to percent, instead of a fraction using Plotnine library in Python?

A MWE of a barplot is as follows:

from plotnine import *
from plotnine.data import mpg

p = ggplot(mpg) + geom_bar(aes(x='manufacturer', fill='class'), position='fill')
print(p)

Which gives the following figure:

Stacked bar chart with y axis as fraction not percent

With ggplot2 in R it is simple, just need to add:

+ scale_y_continuous(labels = scales::percent)

However I have not been able to find how to do this in Plotnine.

Any advise?

like image 519
Camilo Ramirez Avatar asked Oct 03 '18 10:10

Camilo Ramirez


1 Answers

The labels parameter accepts a callable that takes the list of break points as input. All you have to do is to convert each item in the list manually:

scale_y_continuous(labels=lambda l: ["%d%%" % (v * 100) for v in l])
like image 79
João Eduardo Avatar answered Sep 29 '22 13:09

João Eduardo