简体   繁体   中英

plotting rectangles and lineranges with discrete axis in ggplot2

I'm fairly new to 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.

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)

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 :

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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