【发布时间】:2019-09-10 01:32:43
【问题描述】:
我正在尝试将具有三个元素(geom_point、geom_line 和geom_rect)的ggplotly 图表放在一起,它在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 版本:
ggplotly(gg)
有没有办法让ggplotly 图像看起来像基本的ggplot2 图表?
【问题讨论】:
-
我刚刚遇到了同样的问题 - 它似乎源于
ggplotly不支持ymin = -Inf和ymax = Inf的事实。我还没有找到解决方法,但如果我这样做了,我会发布答案! -
谢谢@Clara!我也会这样做