如何在 Python Plotnine barplot 中更改 y 轴以显示百分比 (%)?
How to change the y axis to display percent (%) in Python Plotnine barplot?
如何使用 Python 中的 Plotnine 库将 y 轴更改为百分比,而不是分数?
条形图的MWE如下:
from plotnine import *
from plotnine.data import mpg
p = ggplot(mpg) + geom_bar(aes(x='manufacturer', fill='class'), position='fill')
print(p)
其中给出了下图:
Stacked bar chart with y axis as fraction not percent
在R中使用ggplot2很简单,只需要添加:
+ scale_y_continuous(labels = scales::percent)
但是我没能在 Plotnine 中找到如何做到这一点。
有什么建议吗?
labels
参数接受一个将断点列表作为输入的可调用对象。您所要做的就是手动转换列表中的每个项目:
scale_y_continuous(labels=lambda l: ["%d%%" % (v * 100) for v in l])
这里提出了类似的问题: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)
可以在此处找到其他预定义过滤器:https://mizani.readthedocs.io/en/stable/formatters.html