Search code examples
rggplot2facet-wrapfacet-griddot-plot

How can I make stacked dot plots using a facet in GGplot2? R


I am trying to stack dot plots using a facet in GGplot2.

My first dot plot:

plot1 <- ggplot(marathon, aes(x = MarathonTime, y = first_split_percent)) +
  geom_point()
plot1

enter image description here

My second:

plot2 <- ggplot(marathon, aes(x=MarathonTime, y=km4week)) +
  geom_point()
plot2

enter image description here

I am trying to stack them on top of each other as they share the same x-axis. I have tried using facet_wrap as so:

plot3 <- ggplot(marathon, aes(x = MarathonTime, y = first_split_percent)) +
  geom_point() +
  facet_wrap(km4week~.)
plot3

enter image description here

I have also played around with the 'rows = vars(km4week), cols = vars(MarathonTime)' functions but have had no luck. Is there a way to achieve what I am describing without a facet? Or am I using the Facet function incorrectly? Any help is greatly appreciated!


Solution

  • To stack your two plots using facetting you first have to reshape your data so that your columns become categories of one column or variable which could then be used in facet_wrap.

    Using some fake random example data:

    set.seed(123)
    
    marathon <- data.frame(
      MarathonTime = runif(100, 2, 4),
      first_split_percent = runif(100, 45, 55),
      km4week= runif(100, 20, 140)
    )
    
    library(ggplot2)
    library(tidyr)
    
    marathon_long <- marathon |> 
      pivot_longer(c(first_split_percent, km4week), names_to = "variable")
    
    ggplot(marathon_long, aes(x = MarathonTime, y = value)) +
      geom_point() +
      facet_wrap(~variable, scales = "free_y", strip.position = "right", ncol = 1)