簡體   English   中英

為 Plotly R 中的條形圖添加注釋

[英]Adding annotations for the bar chart in Plotly R

我需要為 2019 年和 2020 年的圖表添加注釋。我到 2020 年有問題。我想按如下所示進行操作,但文本與 2019 年的文本重疊。

在此處輸入圖像描述

quarter <- c("Q1", "Q2", "Q3")
y_18 <- c(10, 16, 23)
y_19 <- c(12, 20, 29)
y_20 <- c(14, NA, NA)
TD <- data.frame(quarter, y_18, y_19, y_20)

fig <- plot_ly(TD, x = ~quarter, y = ~y_18, type = 'bar', name = '2018')
fig <- fig %>% add_trace(y = ~y_19, name = '2019')
fig <- fig %>% add_trace(y = ~y_20, name = '2020')
fig <- fig %>% layout(yaxis = list(title = 'count'), barmode = 'group')
fig <- fig %>% add_annotations( x = TD$quarter,
                                y = TD$y_19,
                                text = c("+2","+4","+6"),
                                xref = "x",
                                yref = "y",
                                showarrow = TRUE)

#my solutions:
fig <- fig %>% add_annotations( x = TD[1,1],
                                y = TD[1,3],
                                text = "+2",
                                xref = "x",
                                yref = "y",
                                showarrow = TRUE)

通過一點手動干預,您可以找出合適的 y 坐標(見下文)。 我離開了所有 3 個坐標,所以如果你想 label 那些帶有 NA 的,只需替換代碼中的空白注釋和 showarrow FALSE 邏輯:

library(plotly)
quarter <- c("Q1", "Q2", "Q3")
y_18 <- c(10, 16, 23)
y_19 <- c(12, 20, 29)
y_20 <- c(14, NA, NA)
TD <- data.frame(quarter, y_18, y_19, y_20)

fig <- plot_ly(TD, x = ~quarter, y = ~y_18, type = 'bar', name = '2018')
fig <- fig %>% add_trace(y = ~y_19, name = '2019')
fig <- fig %>% add_trace(y = ~y_20, name = '2020')
fig <- fig %>% layout(yaxis = list(title = 'count'), barmode = 'group')
fig <- fig %>% add_annotations( x = TD$quarter,
                                y = TD$y_19,
                                text = c("+2","+4","+6"),
                                xref = "x",
                                yref = "y",
                                showarrow = TRUE)

fig %>% add_annotations( x = c(.25, 1.25, 2.25),
                         y = TD$y_20,
                         text = c("+2","",""),
                         xref = "x",
                         yref = "y",
                         showarrow = c(TRUE, FALSE, FALSE))

暫無
暫無

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

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