Search code examples
rggplot2dplyrtidyversegeom-point

How to plot every column of a data frame agains every other column using ggplot and geom point?


I have a data frame with 3 columns and I would like to plot every column versus the other column with geom_point. I am aware of ggpairs function but I would like to do this using regular geom_point().

df <- data.frame(A = rnorm(n = 100, mean = 0, sd = 1),
             B = rnorm(n = 100, mean = 3, sd = 0.5),
             C = rnorm(n = 100, mean =1, sd =2)) %>% mutate(id = 1:100)

Any ideads?


Solution

  • library(tidyverse)
    df_long <- pivot_longer(df, -id)
    df_long |>
      left_join(df_long, join_by(id)) |>
      ggplot(aes(value.x, value.y)) +
      geom_point() +
      facet_grid(name.y ~ name.x)
    

    enter image description here

    As @Axeman suggests, you could use facet_grid(name.y ~ name.x, scales = "free") to trim the blank space. In some cases, arguably in this one, plotting the same range for each variable helps highlight visually their different ranges. In other cases, especially if the variables vary by orders of magnitude, the visual will be clearer using trimmed scales.