How to Plot One Variable against Multiple Others



How to Plot One Variable against Multiple Others

This article shows how to visualize one numeric variable against multiple others.

Prerequisites

Load required R package and set the default theme to theme_bw() :

library(tidyverse)
theme_set(
  theme_bw() +
    theme(legend.position = "top")
  )

Data preparation

  • Demo data:
head(iris, 3)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          5.1         3.5          1.4         0.2  setosa
## 2          4.9         3.0          1.4         0.2  setosa
## 3          4.7         3.2          1.3         0.2  setosa
  • Gather all variables into key-value pairs, except your variables of interest:
iris.gathered <- iris %>%
  as_data_frame() %>%
  gather(key = "variable", value = "value",
         -Sepal.Length, -Species)

head(iris.gathered, 3)
## # A tibble: 3 x 4
##   Sepal.Length Species variable    value
##          <dbl> <fct>   <chr>       <dbl>
## 1          5.1 setosa  Sepal.Width   3.5
## 2          4.9 setosa  Sepal.Width   3  
## 3          4.7 setosa  Sepal.Width   3.2

Visualization

Plot the variable Sepal.Length against the other variables:

ggplot(iris.gathered, aes(x = value, y = Sepal.Length)) +
  geom_point(aes(color = Species)) +
  facet_wrap(~variable)+
  scale_color_viridis_d()





No Comments

Post a Reply