You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为R语言Plotly饼图添加数值与百分比切换按钮

实现Plotly饼图数值与百分比的切换按钮

要给饼图添加数值/百分比切换按钮,核心是通过Plotly的updatemenus配置按钮,点击时修改饼图的textinfo属性,同时保证显示格式符合需求。以下是修改后的完整代码:

output$t <- renderPlotly({
    data <- dt() %>%
      group_by(Type) %>%
      summarise(sum = sum(Premium)/1000000) %>%
      plot_ly(labels = ~Type,
              textinfo = 'percent+value', # 默认同时显示两者
              textfont = list(color = "black"),
              values = ~sum, # 保留原始数值,避免影响百分比计算
              marker = list(colors = color_product),
              sort = FALSE
      ) %>%
      add_pie(hole = 0.4) %>%
      layout(
        xaxis = list(zeroline = F, showline = F, showticklabels = F, showgrid = F),
        yaxis = list(zeroline = F, showline = F, showticklabels = F, showgrid = F),
        # 配置切换按钮
        updatemenus = list(
          list(
            type = "buttons",
            direction = "right",
            x = 0.7, y = 1.2, # 按钮位置调整
            buttons = list(
              list(
                label = "数值+百分比",
                method = "restyle",
                args = list(list(textinfo = "percent+value"))
              ),
              list(
                label = "仅数值",
                method = "restyle",
                args = list(list(textinfo = "value", 
                                text = ~format(sum, nsmall = 2, digits = 2)))
              ),
              list(
                label = "仅百分比",
                method = "restyle",
                args = list(list(textinfo = "percent"))
              )
            )
          )
        )
      )
})

关键说明:

  • 移除了values参数里的format,保留原始sum数值,确保百分比计算准确,同时方便切换时重新格式化数值显示。
  • 通过updatemenus定义三个按钮,使用restyle方法动态修改饼图的textinfo属性,实现三种显示模式的切换。
  • 切换到“仅数值”时,通过text参数指定格式化规则,保证数值显示两位小数。

内容的提问来源于stack exchange,提问作者Ernesto Lugo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 09:15:33