向ggplotly绘图添加垂直线垂直线、ggplotly

2023-09-06 08:05:08 作者:拱手江河讨你欢

我正在尝试构建一个结合 ggplot2plotly 的情节.两条垂直线出现在纯 ggplot2 上,但是一旦我在其上调用 plotly::ggplotly ,它们就会消失.如何使数据也出现在 ggplotly 版本上?如果你有一个只使用 plot_ly 的解决方案,那也很好.

I am trying to build a plot combining ggplot2 and plotly. The two vertical lines appear on pure ggplot2, but once I call plotly::ggplotly on it, they go away. How can I make the data also appear on the ggplotly version? If you have a solution using only plot_ly, that would be fine too.

数据:

df <- structure(list(date = structure(c(17226, 17257, 17287, 17318, 
17348, 17379, 17410, 17440, 17471, 17501, 17226, 17257, 17287, 
17318, 17348, 17379, 17410, 17440, 17471, 17501, 17226, 17257, 
17287, 17318, 17348, 17379, 17410, 17440, 17471, 17501), class = "Date"), 
    n = c(253L, 217L, 257L, 166L, 121L, 56L, 68L, 62L, 142L, 
    20L, 174L, 228L, 180L, 158L, 80L, 39L, 47L, 54L, 107L, 12L, 
    93L, 74L, 47L, 49L, 55L, 16L, 52L, 53L, 32L, 3L), act = c("a", 
    "a", "a", "a", "a", "a", "a", "a", "a", "a", "b", "b", "b", 
    "b", "b", "b", "b", "b", "b", "b", "c", "c", "c", "c", "c", 
    "c", "c", "c", "c", "c")), class = "data.frame", row.names = c(NA, 
-30L), .Names = c("date", "n", "act"))

facts_timeline <- structure(list(Date = structure(c(17507, 17293), class = "Date"), 
    ShortDescription = c("Marketing Campaign", "Relevant Fact 1"
    )), row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame"
), spec = structure(list(cols = structure(list(Date = structure(list(
    format = ""), .Names = "format", class = c("collector_date", 
"collector")), Tenant = structure(list(), class = c("collector_character", 
"collector")), ShortDescription = structure(list(), class = c("collector_character", 
"collector")), LongDescription = structure(list(), class = c("collector_character", 
"collector"))), .Names = c("Date", "Tenant", "ShortDescription", 
"LongDescription")), default = structure(list(), class = c("collector_guess", 
"collector"))), .Names = c("cols", "default"), class = "col_spec"), .Names = c("Date", 
"ShortDescription"))

制作情节的代码:

p <- df %>% 
  ggplot(aes(date, n, group = act, color = act)) + 
  geom_line() + 
  geom_vline(data = facts_timeline, aes(xintercept = Date))

在这里你可以看到两条垂直线:

Here you can see the two vertical lines:

p

但不在这里:

ggplotly(p)

推荐答案

只需将 xintercept 设置为数字,一切都会正常.

Simply set the xintercept to numeric, and everything will work.

p <- df %>% 
  ggplot(aes(date, n, group = act, color = act)) + 
  geom_line() + 
  geom_vline(data = facts_timeline, aes(xintercept = as.numeric(Date)))

p

ggplotly(p)