簡體   English   中英

如何在 R 中使用 plot_ly() 為堆積條形圖設置標簽

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

我正在嘗試使用 R 中的plot_ly() plot 堆疊條形圖。 問題是我無法為欄中的每個堆棧放置標簽。

這是我的數據框

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

誰能幫我解決這個問題?

提前致謝。

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)

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM