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

2

16

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?

Cider answered 3/10, 2018 at 10:43 Comment(0)
A
16

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])
Audiophile answered 4/10, 2018 at 17:45 Comment(0)
T
19

similar question raised here: https://github.com/has2k1/plotnine/issues/152

from plotnine import *
from plotnine.data import mpg
from mizani.formatters import percent_format

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

other predefined filters can be found here: https://mizani.readthedocs.io/en/stable/formatters.html

Townspeople answered 29/10, 2018 at 18:13 Comment(1)
(+1) formatters is now deprecated and one should use labelsFirmament
A
16

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])
Audiophile answered 4/10, 2018 at 17:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.