How do I combine scatterplots to form a scatterplot matrix with common X axis for varied Y axis?

485 views Asked by At

my plot looks like this

enter image description here

This is what I've tried. I make individual scatter plots and combined them together with grid.arrange.

data(methylmercurydata) 
p1 <- ggplot(data=methylmercurydata,aes(x=MeHg, y=logTHg)) + geom_point()
p2 <- ggplot(data=methylmercurydata,aes(x=MeHg, y=OM)) + geom_point()
p3 <- ggplot(data=methylmercurydata,aes(x=MeHg, y=FeRB)) + geom_point()
grid.arrange(p1,p2,p3)
2

There are 2 answers

0
jared_mamrot On

It's not clear to me what you mean by 'scatterplot matrix', but if you want to make a correlation matrix, you can use ggforce (e.g. per https://ihaddadenfodil.com/post/it-s-a-bird-it-s-a-plane-it-s-a-ggforce-function/):

library(tidyverse)
library(ggforce)
library(palmerpenguins)

ggplot(penguins, aes(col = sex)) +
  geom_autopoint(na.rm = TRUE) +
  facet_matrix(rows = vars(bill_length_mm:body_mass_g),
               switch = "x")

example plot

2
bradisbrad On

Easiest way to do this would likely be using dplyr::facet_wrap() after creating a longer table.

Something like:

library(tidyverse)

methylmercurydata %>%
    pivot_longer(cols = c(logTHg, OM, FeRB), names_to = 'metric') %>%
    ggplot() +
    geom_point(aes(MeHG, value)) +
    facet_wrap(~metric)

Edit: r2evans makes a good point; if you need separate scales across y, you can use scales = 'free_y' within the facet_wrap call. Likewise, scales = 'free_x' would provide different x axes, and scales = 'free' would provide different scales for each axis. One other thing to consider when recreating the above plot would be specifying the ncol argument as well, in this case ncol = 1.