Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visualize events on a timeline with ggplot

Tags:

r

ggplot2

Goal

I like to visualize at which positions an event occurred. The data contains a simple counter (x) ranging from 1 to n() and a column hit which is either x when the event occurred or NA otherwise.

Data

library(dplyr)
library(ggplot2)
set.seed(6102023)
dat <- tibble(x = 1:5000) %>%
  mutate(hit = if_else(x %in% sample(n(), round(.2 * n())), "x", NA_character_))

Plot

ggplot(dat) +
  geom_text(aes(x = x, y = 1, label = if_else(is.na(hit), "", "|"))) +
  theme_minimal()

Rug like plot which shows a "|" character at each position where an event occured

I am not happy with this visualization:

  1. Although there was an event in only 20% of the cases, the timeline looks very dense giving the visual impression that there were by far more events.
  2. We are wasting a lot of white space.

So I would need a crisper visualization which helps me to judge whether the events were distributed randomly or whether there was any sort of pattern.

like image 331
thothal Avatar asked Nov 01 '25 11:11

thothal


1 Answers

Here's an attempt, with alpha and geom_segment:

ggplot(na.omit(dat)) +
  geom_segment(aes(x = x, xend = x, y = 0, yend = 1), color = "red", alpha = .1) +
  theme_minimal() +
  theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(), 
        axis.ticks.y=element_blank())

enter image description here


An other option could be to use geom_histogram with the share of events per bin; binwidth controls the width of the bin along the x axis. With this method, you see clearly that each bin of 100 observations has

ggplot(na.omit(dat)) + aes(x = x) +
  geom_histogram(aes(y = after_stat(count / sum(count))), binwidth = 100, fill = "white", color = "black") +
  scale_y_continuous(labels = scales::percent_format()) + 
  theme_minimal()

enter image description here

like image 198
Maël Avatar answered Nov 03 '25 03:11

Maël



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!