如何在 mizani.labels.percent() 中设置准确度

问题描述 投票:0回答:1

我可以使用 mizani.label.percent 或其他 mizani 格式化程序来显示带有一位小数的 geom_label 吗?下面的代码有效,但四舍五入为整数。

import polars as pl
from plotnine import * 
import mizani.labels as ml

df = pl.DataFrame({
  "group": ["A", "B"], 
  "rate": [.511, .634]
})

(
    ggplot(df, aes(x="group", y="rate", label="ml.percent(rate)"))
    + geom_col()
    + geom_label()
    + scale_y_continuous(labels=ml.percent)
)

[![在此处输入图像描述][1]][1]

(
    ggplot(df, aes(x="group", y="rate", label="ml.percent(rate, accuracy=.1)"))
    + geom_col()
    + geom_label()
    + scale_y_continuous(labels=ml.percent)
)

Plot9ineError:“无法评估‘标签’映射:‘ml.percent(rate,accuracy=.1)’(原始错误:call()得到了意外的关键字参数‘accuracy’)” [1]:https://i.sstatic.net/F3vwvsVo.png

python plotnine
1个回答
0
投票

经过相当多的尝试后,我找到了解决方案:

您可以直接对

geom_label
内的标签进行格式化,以达到想要的百分比显示:

import polars as pl
from plotnine import * 

df = pl.DataFrame({
  "group": ["A", "B"], 
  "rate": [.511, .634]
})

(
    ggplot(df, aes(x="group", y="rate", label="rate"))
    + geom_col()
    + geom_label(format_string='{:.1%}')
)

结果:

Bar chart showing rates for two groups A and B, with group B having a higher rate of 63.4% compared to group A's 51.1%.

此外,您可以像这样替换 y 轴上的

mizani
格式以获得相同的结果:

import polars as pl
from plotnine import * 

df = pl.DataFrame({
  "group": ["A", "B"], 
  "rate": [.511, .634]
})

(
    ggplot(df, aes(x="group", y="rate", label="rate"))
    + geom_col()
    + geom_label(format_string='{:.1%}')
    + scale_y_continuous(labels=lambda l: ["{:.1f}%".format(v * 100) for v in l])
)
© www.soinside.com 2019 - 2024. All rights reserved.