将ggplot2转换为ggplotly时geom_rect丢失

8

我试图用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?")

ggplot 图像显示了使用 geom_rect 实现的期望输出。

gg

enter image description here

现在是 ggplotly 版本:

注:该内容涉及 IT 技术,下文仅供参考。
ggplotly(gg)

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

输入图片说明


3
我遇到了和你一样的问题 - 似乎是因为 ggplotly 不支持 ymin = -Infymax = Inf。我还没有找到解决方法,但如果我找到了,我会发布一个答案! - Clara
谢谢@Clara!我会做同样的事情。 - Agrosel
1个回答

3

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接