0

I want to draw a kind of box plot, but the graph will represent the starting and endpoint of the dataset. For instance, I can represent my input below, but I draw the output in excel.

dt<-data.frame(Start=c(5,15,22), End=c(10,21,38))

enter image description here

henryTi
  • 131
  • 1
  • 8

1 Answers1

3

You could use geom_rect:

library(dplyr)
library(ggplot2)

dt %>% 
  mutate(group = factor(seq(n())), 
         ymin = seq(n()), 
         ymax = seq(n()) + 1) %>%
  ggplot() +
  geom_rect(aes(xmin = Start, xmax = End, ymin = ymin, 
                ymax = ymax, fill = group), color = "gray50") +
  scale_y_reverse(expand = c(0.5, 0.5), breaks = 0:5) +
  scale_x_continuous(breaks = 0:10 * 5) +
  scale_fill_manual(values = c("#ea3323", "#bdd6ac", "#779de6")) +
  theme_bw() +
  theme(legend.position = "none",
        axis.text.y = element_blank(),
        axis.ticks.length.y = unit(0, "pt"),
        panel.grid.minor = element_blank())

enter image description here

Or, for a closer reproduction with a bit more code:

dt %>% 
  mutate(group = factor(seq(n())), 
         ymin = seq(n()), 
         ymax = seq(n()) + 1) %>%
  ggplot() +
  geom_rect(aes(ymin = 1, ymax = 2, xmin = -Inf, xmax = Inf),
            fill = "#00000004") +
  geom_rect(aes(ymin = 3, ymax = 4, xmin = -Inf, xmax = Inf),
            fill = "#00000004") +
  geom_rect(aes(xmin = Start, xmax = End, ymin = ymin, 
                ymax = ymax, fill = group), color = "gray50") +
  scale_y_reverse(expand = c(0.25, 0.25), breaks = 0:5) +
  scale_x_continuous(breaks = 0:10 * 5, limits = c(0, 40)) +
  scale_fill_manual(values = c("#ea3323", "#bdd6ac", "#779de6")) +
  theme_bw() +
  theme(legend.position = "none",
        axis.text.y = element_blank(),
        axis.ticks.length.y = unit(0, "pt"),
        panel.grid.minor = element_blank(),
        panel.border = element_blank(),
        axis.line = element_line(color = "black")
        )

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87