Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Connect segment lines with ggplot

I’m trying to draw a bus schedule diagram with ggplot. On the X axis I want bus stops and on the Y axis I want time. I’m nearly there, but I can’t find the way to make a horizontal line between each travel. Here’s my plot and the dataframe.

ggplot(dat,
       aes(x = from,
           xend = to,
           y = departure,
           yend = arrival,
           )) +
  geom_segment() 
  geom_line()

tibble::tribble(
              ~from, ~to, ~departure,   ~arrival,
                "a", "b", "01:00:00", "02:00:00",
                "b", "a", "02:10:00", "03:10:00",
                "a", "b", "03:20:00", "04:20:00",
                "c", "b", "02:30:00", "03:15:00",
                "b", "c", "03:35:00", "04:30:00",
                "c", "b", "04:40:00", "05:30:00"
              )

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One option would be to use dplyr::lead to prepare a dataset containing the coordinates of the connecting segments like so:

library(ggplot2)
library(dplyr)
library(tidyr)

hlines <- df |> 
  mutate(departure = ifelse(lead(from) == to, lead(departure), NA),
         from = to) |> 
  tidyr::drop_na()

ggplot(df, aes(x = from, xend = to, y = departure, yend = arrival)) +
  geom_segment() +
  geom_segment(data = hlines) 

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading