简体   繁体   中英

Plot rectangles using geom_rect with continous x-axis and discrete values in y-axis (R)

I am trying to plot rectangles in the x-axis for different classes in the y-axis. I want to do this with geom_rect , but I don't want to use y_min and y_max since I want these to be determined by the classes (ie factors) I have in my data.

I managed to get the plot I want changing the breaks and the tick labels manually, but I am sure there must be a better way to do this.

Small toy example:

data <- data.frame(x_start = c(0, 2, 4, 6),
                   x_end = c(1, 3, 5, 7),
                   y_start = c(0, 0, 2, 2),
                   y_end = c(1, 1, 3, 3),
                   info = c("x", "x", "y", "y"))

Original plot:

ggplot(data ,aes(xmin=x_start, xmax=x_end, ymin=y_start, ymax=y_end, fill=info)) + geom_rect()

在此处输入图像描述

Plot that I want:

ggplot(data ,aes(xmin=x_start, xmax=x_end, ymin=y_start, ymax=y_end, fill=info)) + geom_rect() +
        scale_y_continuous(breaks = c(0.5,2.5), labels = c("x","y"))

在此处输入图像描述

library(dplyr)
y_lab <- data %>%
  distinct(y_end, y_start, info) %>%
  mutate(y_mid = (y_end + y_start)/2)

ggplot(data, aes(xmin=x_start, xmax=x_end, ymin=y_start, ymax=y_end, fill=info)) +
  geom_rect() +
  scale_y_continuous(breaks = y_lab$y_mid, labels = y_lab$info)

在此处输入图像描述

Or using geom_tile :

ggplot(data, aes(x = (x_start + x_end)/2, y = info, fill=info, width = 1)) +
  geom_tile()

在此处输入图像描述

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