【问题标题】:How to set labels for stacked bar chart using plot_ly() in R如何在 R 中使用 plot_ly() 为堆积条形图设置标签
【发布时间】:2020-05-07 05:16:15
【问题描述】:

我正在尝试在 R 中使用 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】:

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)

【讨论】:

  • 是否有可能使文本标签居中?
猜你喜欢
  • 1970-01-01
  • 2011-04-07
  • 1970-01-01
  • 2019-10-02
  • 2013-12-22
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多