How to Plot One Variable against Multiple Others


Warning: Use of undefined constant access_s2member_level2 - assumed 'access_s2member_level2' (this will throw an Error in a future version of PHP) in /home/www/datanovia/en/wp-content/themes/lms-child/framework/loops/content-single.php on line 56


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()


Warning: Use of undefined constant access_s2member_level2 - assumed 'access_s2member_level2' (this will throw an Error in a future version of PHP) in /home/www/datanovia/en/wp-content/themes/lms-child/framework/loops/content-single.php on line 118




No Comments

Post a Reply