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

Time:11-24

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 (i.e. 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()

enter image description here

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

enter image description here

CodePudding user response:

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)

enter image description here

Or using geom_tile:

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

enter image description here

  • Related