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()
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"))
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)
Or using geom_tile
:
ggplot(data, aes(x = (x_start x_end)/2, y = info, fill=info, width = 1))
geom_tile()