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

Plot crosses on time axis for a binary dependent variable

I want to use ggplot2 to plot a binary variable over time, such that whenever we observe the event (y = 1) for a given individual (id), there is a cross (or point) on the x-axis.

Here is some data:

access <- rbinom(n=500,size=1,prob=0.40)
id = rep(1:10, each = 50)   
day_id = rep(1:50, 10)
da = data.frame(access = access, id = id, day_id = day_id)

Currently I’m using ggplot2 in the following way:

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

  da %>% ggplot(aes(x = day_id, y = access)) + geom_point() + facet_wrap(~id)

This leads to this result:
Result ggplot2

But I want it to look like this (with crosses or points reflecting whether there was access; and the x_axis reflecting a sequence of 50 days per individual):
Target plot

Where each line represents one id.

>Solution :

library(ggplot2)
library(dplyr)

da %>% ggplot(aes(x = day_id, y = factor(id))) + 
  geom_point(data=filter(da, access==1)) +
  geom_line() + 
  labs(y="id") + 
  theme_classic()

enter image description here

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