如何在R中使用plot_ly()为堆叠条形图设置标签?

问题描述 投票:0回答:1

我试图用以下方法绘制叠加条形图 plot_ly() 问题是我无法为每一个堆栈放置标签。

这是我的数据框架

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))

这是绘制叠加条形图的代码。

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))

谁能帮我解决这个问题?

先谢谢你。

r label plotly visualization stacked-chart
1个回答
0
投票

在add_annotation中调用的y轴需要一个小小的变通方法,如下图。

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

© www.soinside.com 2019 - 2024. All rights reserved.