代码之家  ›  专栏  ›  技术社区  ›  Joe

如何在mizani.labels.epercent()中设置精度

  •  1
  • Joe  · 技术社区  · 7 月前

    我能用吗 mizani.label.percent 或者使用另一个mizani格式化程序来显示带有一个小数位的geom标签?下面的代码可以工作,但四舍五入为整数。

    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)
    )
    

    enter image description here

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

    执行此操作时,我收到以下错误:

    PlotnineError: "Could not evaluate the 'label' mapping: 'ml.percent(rate, accuracy=.1)' (original error: __call__() got an unexpected keyword argument 'accuracy')"
    
    1 回复  |  直到 7 月前
        1
  •  2
  •   m-sarabi    7 月前

    经过一段时间的试验,我找到了一个解决方案:

    您可以直接在 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="rate"))
        + geom_col()
        + geom_label(format_string='{:.1%}')
        + scale_y_continuous(labels=ml.percent)
    )
    

    结果:

    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%.

    此外,您可以替换 mizani 按如下方式在y轴上进行格式化,以获得相同的结果:

    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])
    )
    
    推荐文章