How to plot 1/0 data and continuous data

Viewed 39

I would like to have a plot that looks like this: enter image description here

Essentially I have a data frame that looks like this:

      Class Frame  X1  Y1  X2  Y2 xcentre 
1      0     1     465 570 577 698   521.0  
2      0     2     465 570 577 699   521.0   
3      0     3     465 570 577 699   521.0   
4      0     4     465 570 577 699   521.0   
5      0     5     464 570 577 699   520.5   
6      0     6     464 570 577 699   520.5   
7      0     7     464 570 576 699   520.0   
8      0     8     464 570 576 699   520.0   
9      0     9     464 570 576 699   520.0       
10     0    10     464 570 576 699   520.0   

And I would like to plot the xcentre (red line in the image above) and a bar for when class=1. class is a binary (0/1). Can anyone help me with that?

1 Answers

There are a number of ways to get something like you are asking for. The labels outside the plot usually require a bit of fiddling with {ggplot2}, but the rest is pretty straightforward. I also have an option using faceting for the labeling which has some tradeoffs.

library(tidyverse)

set.seed(4)
d <- tibble(frame = 1:200,
            class = as.numeric(c(rep(0, 50), 
                      rep(1, 150))),
            xcenter = c(520 + cumsum(sample(-3:3, 50, T)),
                        520 + cumsum(sample(-30:30, 150, T))))


d %>% 
  mutate(class = as.logical(class)) %>% 
  ggplot(aes(frame, xcenter)) +
  geom_line(color = "red") +
  geom_line(aes(y = min(xcenter)-2, alpha = class), color = "blue", linewidth = 5, show.legend = F) +
  geom_text(data = data.frame(label = c("movement", "interaction"), y = c(520, min(d$xcenter))), 
            x = -20, aes(label = label, y = y), hjust = 1) +
  scale_alpha_manual(values = c(0, 1)) +
  coord_cartesian(clip = 'off') +
  theme(axis.title.y = element_blank(),
        plot.margin = unit(c(0.5, 0.5, 0.5, 4), "lines"))


# alternative with faceting
d %>% mutate(type = "movement") %>% 
  bind_rows(d %>% mutate(type = "interaction")) %>% 
  mutate(type = fct_rev(type)) %>% 
  ggplot(aes(frame)) +
  geom_line(data = ~filter(.x, type == "movement"),
            aes(y = xcenter), color = "red") +
  geom_col(data = ~filter(.x, type != "movement"),
           aes(y = 25*class), fill = "blue") +
  facet_grid(rows = "type", scales = "free_y", space = "free_y") +
  theme(axis.title.y = element_blank())

Created on 2022-09-22 by the reprex package (v2.0.1)

Related