我试图用ggplotly
创建一个包含三个元素(geom_point
,geom_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
现在是 ggplotly 版本:
注:该内容涉及 IT 技术,下文仅供参考。ggplotly(gg)
有没有办法让
ggplotly
图像看起来像基本的ggplot2
图表?
ggplotly
不支持ymin = -Inf
和ymax = Inf
。我还没有找到解决方法,但如果我找到了,我会发布一个答案! - Clara