在 ggplot2 中绘制具有离散轴的矩形和线性范围

plotting rectangles and lineranges with discrete axis in ggplot2

我对 Whosebug 还很陌生。 我想绘制矩形而不是线性范围,因为我想要一个黑色边框。实际上我的教授想要一个黑色边框,但这不是 Whosebug 的问题。

加载库并创建虚拟数据集

library(tidyverse)

mydat <- tibble(
       mymsmt = rep(c("bio", "bio", "den", "den"), 2),
       mylvl = c("NT", "till", "NT", "till", "no", "yes", "no", "yes"),
       mytrt = c(rep("tillage", 4), rep("herbicides", 4)),
       est = c(-60, -13, -65, -40, -16, -24, -49, -50),
       cilow = c(-85, -48, -78, -56, -61, -60, -68, -64),
       ciup = c(8, 45, -44, -18, 79, 42, -20, -31)) %>%
       # Dummy code mylvls as numeric
       mutate(mylvln = rep(c(1, 2), 4))  

如果我只用线性范围绘图,它就可以工作(我还不允许嵌入图像)

ggplot(mydat, aes(est, mylvl)) + 
  geom_linerangeh(aes(xmin = cilow, xmax = ciup), color = "blue", size = 5) +
  # geom_rect(aes(xmin = cilow, xmax = ciup, 
  #               ymin = mylvln - 0.2, ymax = mylvln + 0.2), 
  #           fill = "red", color = "black") +
  geom_point() + 
  facet_grid(mytrt ~ mymsmt, scales = "free")

只用矩形绘图,失败,有 错误:提供给连续刻度的离散值

ggplot(mydat, aes(est, mylvl)) + 
  #geom_linerangeh(aes(xmin = cilow, xmax = ciup), color = "blue", size = 5) +
  geom_rect(aes(xmin = cilow, xmax = ciup, 
                 ymin = mylvln - 0.2, ymax = mylvln + 0.2), 
             fill = "red", color = "black") +
  geom_point() + 
  facet_grid(mytrt ~ mymsmt, scales = "free")

绘制线性范围,由矩形覆盖,作品, 您可以在背景中看到线性范围

ggplot(mydat, aes(est, mylvl)) + 
  geom_linerangeh(aes(xmin = cilow, xmax = ciup), color = "blue", size = 5) +
  geom_rect(aes(xmin = cilow, xmax = ciup, 
                ymin = mylvln - 0.2, ymax = mylvln + 0.2), 
            fill = "red", color = "black", alpha = 0.5) +
  geom_point() + 
  facet_grid(mytrt ~ mymsmt, scales = "free")

为什么?它有效,我得到了我想要的数字,但我不知道为什么。感谢您的帮助!

您也可以使用 geom_tile 代替 geom_rect:

ggplot(mydat, aes(est, mylvl)) + 
  geom_tile(aes(width = ciup-cilow, height=0.1),  fill="red", color="black") +
  geom_point() + 
  facet_grid(mytrt ~ mymsmt, scales = "free")