2
votes

I'm trying to create a simple bar chart using the plotly package in R. I want to add labels above each bar, but I've only be able to successfully add in the counts. Is it all possible to add in percentages next to each count? This is what I have:

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)

The output: enter image description here

I'm wondering if I can add in the percentages for each category. Greatly appreciate any suggestions!

1

1 Answers

1
votes

You can add the percentages next to the counts via text = ~paste0(count, " (", scales::percent(count / sum(count)), ")") where I use scales::percent for nice formatting. Using mtcars as example data, try this:

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