gpt4 book ai didi

r - 将 ggplot2 转换为 ggplotly 时缺少 geom_rect

转载 作者:行者123 更新时间:2023-12-03 17:14:01 26 4
gpt4 key购买 nike

我正在尝试整理一个 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 版本:
ggplotly(gg)

enter image description here

有什么办法可以得到 ggplotly图像看起来像基本 ggplot2图表?

最佳答案

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

关于r - 将 ggplot2 转换为 ggplotly 时缺少 geom_rect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55767599/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com