在ggplotly线图中填充背景间隔

Lut*_*ett 2 background r fill ggplot2 plotly

我正在尝试填充折线图的背景ggplot以指示白天/夜间时段。这个答案中的方法效果很好,但我想使用交互式地显示它们ggplotly,并且由于这个错误而成为一个问题,其中 ggplotly 不喜欢 -Inf 和 Inf 用作 y 限制geom_rect。有谁知道可以与 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
Run Code Online (Sandbox Code Playgroud)

产生这个可爱的人物: 具有填充背景的 ggplot 线图

但是,如果您这样做:

ggplotly(p)
Run Code Online (Sandbox Code Playgroud)

你失去了背景填充: 在此输入图像描述

Azi*_*ziz 6

As juljo mentioned in his comment, the issue is the rectangles' y-range.

To resolve this issue:

  • Plot your data first

    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))
    
    Run Code Online (Sandbox Code Playgroud)
  • Get the y-range of the plot

        ylims = ggplot_build(p)$layout$panel_params[[1]]$y.range
    
    Run Code Online (Sandbox Code Playgroud)
  • Use the y-range to create the rectangles and add them to the plot

        p = p + 
            geom_rect(data = rects, aes(xmin = xstart, xmax = xend, ymin = ylims[1], ymax = ylims[2], fill = col), alpha = 0.4)
    
    Run Code Online (Sandbox Code Playgroud)

p:

在此输入图像描述

ggplotly(p):

在此输入图像描述