将ggplot2转换为ggplotly时缺少geo_rect

问题描述 投票:4回答:1

我正在尝试将具有三个元素(ggplotlygeom_pointgeom_line)的geom_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版本:

ggplotly(gg)

enter image description here

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

r ggplot2 plotly ggplotly
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.