【问题标题】:Filling area above square in grey ggplot2灰色ggplot2正方形上方的填充区域
【发布时间】:2021-04-20 13:28:26
【问题描述】:

我正在尝试用浅灰色填充正方形上方和右侧的区域。正方形内的背景应该是白色的,里面的点仍然可见。正方形上方和右侧的背景应该是浅灰色的,并且那里的点也是可见的。

“fill=blue”和“alpha=0”只是在那里获得白色区域的一种糟糕的解决方法,但那里并不真正需要蓝色。

这是一个可重复的简短示例

data_Z_pairs <- data.frame(Z = c(0.20, 0.1, 0.03), Z_tild = c(0.15, 0.03, 0.02))

p1 <- ggplot(data_Z_pairs, aes(Z, Z_tild))
p2 <- p1 + geom_point() + 
  theme_bw()  +
  theme(panel.grid = element_blank()) +
  geom_abline(slope=1, intercept = 0, linetype = "dashed") +  
  geom_rect(mapping=aes(xmin=0, xmax=t0, ymin=0, ymax=t0, fill ="blue"), 
            alpha=0, color = "black") #


p2

到目前为止,我已经以某种方式使用“geom_polygon”进行了尝试,但无法达到我想要的结果

【问题讨论】:

    标签: r ggplot2 graph data-visualization


    【解决方案1】:

    试试:

    data_Z_pairs <- data.frame(Z = c(0.20, 0.1, 0.03), Z_tild = c(0.15, 0.03, 0.02))
    
    
    library(ggplot2)
    
    t0 <- 0.05
    
    
    ggplot(data_Z_pairs, aes(Z, Z_tild))+
      geom_point() + 
      geom_abline(slope=1, intercept = 0, linetype = "dashed") +  
      geom_rect(aes(xmin=0, xmax=t0, ymin=0, ymax=t0), alpha = 0, colour = "black")+
      geom_rect(aes(xmin = t0, xmax = Inf,  ymin = -Inf, ymax = Inf), fill = "gray80", alpha = 0.2)+
      geom_rect(aes(xmin = -Inf, xmax = t0,  ymin = t0, ymax = Inf), fill = "gray80", alpha = 0.2)+
      geom_rect(aes(xmin = -Inf, xmax = 0,  ymin = -Inf, ymax = t0), fill = "gray80", alpha = 0.2)+
      geom_rect(aes(xmin = -0, xmax = t0,  ymin = -Inf, ymax = 0), fill = "gray80", alpha = 0.2)+
      theme_bw()  +
      theme(panel.grid = element_blank())
    

    如果您实际上只希望框上方和右侧的区域为阴影,则按如下方式调整浅灰色 geom_rect 层:

    
    
    ggplot(data_Z_pairs, aes(Z, Z_tild))+
      geom_point() + 
      geom_abline(slope=1, intercept = 0, linetype = "dashed") +  
      geom_rect(aes(xmin=0, xmax=t0, ymin=0, ymax=t0), alpha = 0, colour = "black")+
      geom_rect(aes(xmin = t0, xmax = Inf,  ymin = 0, ymax = Inf), fill = "gray80", alpha = 0.2)+
      geom_rect(aes(xmin = 0, xmax = t0,  ymin = t0, ymax = Inf), fill = "gray80", alpha = 0.2)+
      theme_bw()  +
      theme(panel.grid = element_blank())
    

    或者使用geom_polygon 可以通过提供一个带有角坐标的单独数据框来实现相同的结果:

    pos <- data.frame(x = c(0, 0, Inf, Inf, t0, t0, 0),
                      y = c(t0, Inf, Inf, 0, 0, t0, t0))
    
    ggplot(data_Z_pairs, aes(Z, Z_tild))+
      geom_point() + 
      geom_abline(slope=1, intercept = 0, linetype = "dashed") +  
      geom_rect(aes(xmin=0, xmax=t0, ymin=0, ymax=t0), alpha = 0, colour = "black")+
      geom_polygon(data = pos, aes(x, y), fill = "gray80", alpha = 0.2)+
      theme_bw()  +
      theme(panel.grid = element_blank())
    

    reprex package (v2.0.0) 于 2021-04-20 创建

    【讨论】:

    • 不幸的是,它没有给出我想要的结果。我稍微编辑了我的问题以使事情更清楚。我担心我之前的描述不够详细。
    猜你喜欢
    • 2014-09-17
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    • 2017-11-21
    相关资源
    最近更新 更多