如何为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
相关产品推荐
相关产品推荐

