绘图条形图-向标签添加百分比

时间:2020-04-08 22:43:06

标签: r plotly

我正在尝试使用R中的plotly包创建一个简单的条形图。我想在每个条形上方添加标签,但是我只能成功添加计数。是否可以在每个计数旁边添加百分比?这就是我所拥有的:

fig_valve <- plot_ly(valve_df, 
                    x = ~vlvsz_c, 
                    y = ~count,
                    type = "bar",
                    hoverinfo = "x+y")
fig_valve <- fig_valve %>%
  add_text(text = ~count, 
           textposition = "top", 
           textfont = list(size = 11, color = "black"), 
           showlegend = FALSE) %>%
  layout(title = "",
         xaxis = list(title = "Valve Size", showgrid = FALSE), 
         yaxis = list(title = "Count", showgrid = FALSE),
         showlegend = FALSE,
         font = t)

输出:enter image description here

我想知道是否可以为每个类别添加百分比。非常感谢任何建议!

1 个答案:

答案 0 :(得分:1)

您可以通过text = ~paste0(count, " (", scales::percent(count / sum(count)), ")")在计数旁边添加百分比,在这里我使用scales::percent进行格式化。使用mtcars作为示例数据,请尝试以下操作:

library(plotly)
library(dplyr)
library(scales)

fig_valve <- mtcars %>% 
  count(cyl, name = "count") %>% 
    plot_ly( 
      x = ~cyl, 
      y = ~count,
      type = "bar",
      hoverinfo = "x+y")
fig_valve <- fig_valve %>%
  add_text(text = ~paste0(count, " (", scales::percent(count/sum(count)), ")"), 
           textposition = "top", 
           textfont = list(size = 11, color = "black"), 
           showlegend = FALSE) %>%
  layout(title = "",
         xaxis = list(title = "Valve Size", showgrid = FALSE), 
         yaxis = list(title = "Count", showgrid = FALSE),
         showlegend = FALSE,
         font = t)
fig_valve

enter image description here