我正在尝试填充 ggplot
线图的背景以指示白天/夜间时段。 this answer中的方法效果很好,但我想使用 ggplotly 交互地显示它们,这成为一个问题,因为 this bug ,其中 ggplotly 不喜欢将 -Inf 和 Inf 用作 geom_rect
的 y 限制。有谁知道可以与 ggplotly 一起使用的解决方法吗?
为了便于阅读,我将其他答案中的示例代码粘贴到此处:
library(ggplot2)
dat <- data.frame(x = 1:100, y = cumsum(rnorm(100)))
#Breaks for background rectangles
rects <- data.frame(xstart = seq(0,80,20), xend = seq(20,100,20), col = letters[1:5])
p <- ggplot() +
geom_rect(data = rects, aes(xmin = xstart, xmax = xend, ymin = -Inf, ymax = Inf, fill = col), alpha = 0.4) +
geom_line(data = dat, aes(x,y))
p
但是,如果您这样做:
ggplotly(p)
最佳答案
正如 juljo 在评论中提到的,问题在于矩形的 y 范围。
要解决此问题:
首先绘制数据
library(ggplot2) library(plotly) dat <- data.frame(x = 1:100, y = cumsum(rnorm(100))) #Breaks for background rectangles rects <- data.frame(xstart = seq(0,80,20), xend = seq(20,100,20), col = letters[1:5]) # Only plot the data p <- ggplot() + geom_line(data = dat, aes(x,y))
获取绘图的 y 范围
ylims = ggplot_build(p)$layout$panel_params[[1]]$y.range
使用 y 范围创建矩形并将它们添加到绘图中
p = p + geom_rect(data = rects, aes(xmin = xstart, xmax = xend, ymin = ylims[1], ymax = ylims[2], fill = col), alpha = 0.4)
p
:
ggplotly(p)
:
关于r - 在ggplotly线图中填充背景间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63951513/