简体   繁体   English

在ggplot2中用离散轴绘制矩形和线段

[英]plotting rectangles and lineranges with discrete axis in ggplot2

I'm fairly new to stackoverflow.我对stackoverflow很陌生。 I want to plot rectangles instead of lineranges because I want a black border.我想绘制矩形而不是线条范围,因为我想要一个黑色边框。 Actually my professor wants a black border but that is not an issue for stackoverflow.实际上,我的教授想要一个黑色边框,但这对 stackoverflow 来说不是问题。

Load library and create dummy dataset加载库并创建虚拟数据集

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))  

If I plot with just the linerange, it works (I'm not allowed to embed images yet)如果我只用 linerange 绘图,它就可以工作(我还不允许嵌入图像)

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")

Plot with just rectangles, fails, with Error: Discrete value supplied to continuous scale只绘制矩形,失败,错误:离散值提供给连续比例

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")

Plot with linerange, covered by rectangles, works, You can see the lineranges in the background绘制线段,由矩形覆盖,有效,您可以在背景中看到线段

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")

Why?为什么? It works, I get the figure I want, but I don't know why.它有效,我得到了我想要的数字,但我不知道为什么。 Thanks for your help!谢谢你的帮助!

You can also use geom_tile in place of geom_rect :您还可以使用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")

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM