Search code examples
rlabelplotlyvisualizationstacked-chart

How to set labels for stacked bar chart using plot_ly() in R


I am trying to plot stacked bar chart using plot_ly() in R. The problem is I'm unable to place labels for each stack in the bar.

This is my data frame

df <- data.frame("QuarterYear" = c("2019 Q1","2019 Q2","2019 Q2","2019 Q3","2019 Q3","2019 Q3"), "Size" = c("Medium","Large","Medium","Large","Medium","Small"),
                 "percentage" = c(100,29,71,13,74,13))

This is the code for plotting the stacked bar chart

plot_ly(df, x = df$QuarterYear,
        y = df$percentage,
        type = 'bar',
        name = df$Size,
        text = paste(df$percentage,"%"),
        textposition = 'top',
        hoverinfo = 'text',
        hovertext = paste('Size: ', df$Size,
                          '<br> % of Total count: ', paste(df$percentage,"%")),
        color = df$Size) %>%
  layout(yaxis = list(title = "% of Count", zeroline = FALSE, 
                      showline = FALSE, ticksuffix = "%"), barmode = 'stack',hoverlabel = list(bgcolor= 'white')) %>%
  layout(legend = list(orientation = "h",
                       xanchor = "center",
                       x = 0.5,
                       y = -0.13))

Can anyone help me to solve this?

Thanks in advance.


Solution

  • The y axis called in add_annotation needs a small workaround as below:

    plot_ly(df, x = df$QuarterYear,
            y = df$percentage,
            type = 'bar',
            name = df$Size,
            text = paste(df$percentage,"%"),
            textposition = 'top',
            hoverinfo = 'text',
            hovertext = paste('Size: ', df$Size,
                              '<br> % of Total count: ', paste(df$percentage,"%")),
            color = df$Size) %>%
      layout(yaxis = list(title = "% of Count", zeroline = FALSE, 
                          showline = FALSE, ticksuffix = "%"), barmode = 'stack',
             hoverlabel = list(bgcolor= 'white')) %>%
      layout(legend = list(orientation = "h",
                           xanchor = "center", 
                           x = 0.5,
                           y = -0.13)) %>% 
      add_annotations(text = paste0(df$percentage, "%"), x = df$QuarterYear, 
                      y = unlist(tapply(df$percentage, df$QuarterYear, FUN=cumsum))-(df$percentage/2), 
                      showarrow = FALSE)
    

    enter image description here