Timeseries with Categorical Y axis

Hello everyone,

I'd like to create a plot of two timeseries, in the style of a ridgeplot (see image). So instead of plotting a density, I'd like to plot two timeseries in the same plot, but have them not overlap. The timeseries only take on values of 0 or 1.

image

I've been playing around in R using just geom_line(), but with no succes. The closest I've gotten is with the code below.

Any tips are much appreciated.

library(tidyverse)
  
  df <- data.frame(
    g1 = rbinom(n = 50, size = 1, prob = 0.60),
    g2 = rbinom(n = 50, size = 1, prob = 0.60),
    time = 1:50)
  
  df %>%
    pivot_longer(1:2) %>%
    ggplot(mapping = aes(x = time, y = name, col = value)) +
    geom_line()

Created on 2020-07-27 by the reprex package (v0.3.0)

You should look into dygraph packagel i guess it might help you.

library(ggplot2)
library(ggridges)
set.seed(42)
d <- data.frame(
  x = rep(1:5, 3),
  y = c(rep(0, 5), rep(1, 5), rep(2, 5)),
  height = sample.int(2,15,replace=TRUE) -1
)

ggplot(d, aes(x, y, height = height, group = y)) + 
  geom_density_ridges(stat = "identity", scale = .95)

library(tidyverse)
library(ggridges)


set.seed(42)
df <- data.frame(
  g1 = rbinom(n = 50, size = 1, prob = 0.60),
  g2 = rbinom(n = 50, size = 1, prob = 0.60),
  time = 1:50) %>% pivot_longer(cols = starts_with("g"),
                                names_to = "g",
                               values_to = "height")  

ggplot(df, aes(x=time,y=g, height = height, group = g)) + 
  geom_density_ridges(stat = "identity", scale = .95) 

1 Like

This is very close to what I want.

Any way to get rid of the density stuff? Get rid of the filling in with gray?
Any way to add the the datapoints?

library(tidyverse)

set.seed(42)
df <- data.frame(
  g1 = rbinom(n = 50, size = 1, prob = 0.60),
  g2 = rbinom(n = 50, size = 1, prob = 0.60),
  time = 1:50) %>% pivot_longer(cols = starts_with("g"),
                                names_to = "g",
                               values_to = "height") %>%
  mutate(heightswitch=case_when(height==0 ~ "Off",
                               TRUE ~ "On"),
         yaxis_levels = factor(paste0(g," ",heightswitch)))

ggplot(df, aes(x=time,y= yaxis_levels,group=g)) + 
  geom_point() + geom_line()

1 Like

Thanks so much! That seems perfect

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.