将 ggplot2 转换为 ggplotly 时缺少 geom_rect

Agr*_*sel 5 r ggplot2 plotly ggplotly

我试图把一个ggplotly图形与(三大要素geom_pointgeom_linegeom_rect),它看起来罚款ggplot2。但是,当我转换为 ggplotly 时,geom_rect 消失了。我在想这与inherit.aes功能有关吗?

构建测试数据的代码如下。

library(ggplot2)
library(plotly)

dates_seq = seq.Date(as.Date("2019-03-13"), as.Date("2019-04-21"), by = "1 day")
df = data.frame(ds = dates_seq,
                y = rnorm(length(dates_seq), mean = 50, sd = 5),
                yhat = rnorm(length(dates_seq), mean = 50, sd = 5)
                )
df$yhat_lower = df$yhat - 5
df$yhat_upper = df$yhat + 5

gg <- ggplot(df, aes(x = ds, y = y)) +
    labs(x = 'Date', y = 'Sales') +
      geom_ribbon(aes(ymin = yhat_lower, ymax = yhat_upper), fill = 'blue',
                  alpha = 0.2,
                  na.rm = TRUE)

start_date = as.Date("2019-04-19")
gg <- gg +
  geom_point(na.rm=TRUE) +
  geom_vline(xintercept = as.numeric(as.Date(start_date - lubridate::days(1))), linetype = 2, color = "black") +
  geom_line(aes(y = yhat), color = 'blue',
            na.rm = TRUE) +
  theme_classic()

promo_df = data.frame(xmin = c("2019-03-15", "2019-04-01"), xmax = c("2019-03-18", "2019-04-08"),
                          ymin = -Inf, ymax = Inf, Promo = "Yes")
promo_df$id = 1:nrow(promo_df)
gg = gg +
  geom_rect(data=promo_df, inherit.aes=FALSE,
            aes(xmin=as.Date(xmin),
                xmax=as.Date(xmax),
                ymin=ymin,ymax=ymax,
                group=id, fill = factor(Promo)), alpha=0.2) +
  scale_fill_discrete(name = "On Promo?")
Run Code Online (Sandbox Code Playgroud)

ggplot 图像显示了所需的输出geom_rect

gg
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

现在是 ggplotly 版本:

ggplotly(gg)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

有没有办法让ggplotly图像看起来像基本ggplot2图表?

小智 3

关于 ggplotly 无法支持 ymin/max 参数,Clara 是正确的。最好的解决方法是手动将参数设置为等于上一个(主)层的比例。所以在这种情况下,它等于 0/65。