R plotly 仅显示堆叠条形图中的标签,其中堆叠的百分比值高于 5

R plotly show only labels in the stacked bar chart where percentage value for the stack is above 5

我有一个数据框

df <- data.frame("QuarterYear" = c("2019 Q1","2019 Q1","2019 Q2","2019 Q2","2019 Q3","2019 Q3","2019 Q3"), "Size" = c("Medium","Small","Large","Medium","Large","Medium","Small"),
                 "percentage" = c(98,2,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))%>%
  add_annotations(text = paste0(df$percentage, "%"),
                  x = df$QuarterYear,
                  y = unlist(tapply(df$percentage, df$QuarterYear, FUN=cumsum))-(df$percentage/2),
                  showarrow = FALSE)

得到的输出是

但是 2% 不可见,因为堆栈的大小较小以容纳该值。是否有可能仅在值大于 5 时显示标签?

提前致谢!!

对注释文本使用 ifelse() 函数。

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 = ifelse(df$percentage > 2, paste0(df$percentage, "%"), ""),
                  x = df$QuarterYear,
                  y = unlist(tapply(df$percentage, df$QuarterYear, FUN=cumsum))-(df$percentage/2),
                  showarrow = FALSE)