1

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!

Garrett
  • 43
  • 5

1 Answers1

2

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)

stefan
  • 90,330
  • 6
  • 25
  • 51
  • Wow, thank you! I also realized that I could use cowplot::plot_grid() to avoid faceting. I am going to use your solution though! – Garrett Feb 16 '23 at 18:03
  • 1
    Yeah. Of course. That would be the second approach. But I would prefer to use the `patchwork` package for this. In general it works better when it comes to glueing plots. – stefan Feb 16 '23 at 18:06