r - 在ggplotly线图中填充背景间隔

标签 r ggplot2 background plotly fill

我正在尝试填充 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

产生这个可爱的人物: ggplot line graph with filled background

但是,如果您这样做:

ggplotly(p)

你失去了背景填充: enter image description here

最佳答案

正如 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:

enter image description here

ggplotly(p):

enter image description here

关于r - 在ggplotly线图中填充背景间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63951513/

相关文章:

r - 最短路径函数在 R igraph 中返回错误路径

r - 在 R 中按均值(而不是中值)对箱线图进行排序

android ftp上传已停止错误

r - 为什么我没有使用 ggplot2 获得两个图例?

java - 向一个 JFrame 添加多种类型的背景

html - 如何编辑背景大小?

r - map() 中是否有 "next"等效项

mysql - R在多种编码存储中读取SQL并以utf-8工作

r - ggplot:删除图例中的NA因子水平

r - 在ggplot中接受类 "Date"的水平和垂直线有问题吗?