首页 > 解决方案 > 一个因变量和多个独立变量的 ggplot

问题描述

当变量总是相同并且只是改变变量时,是否可以创建多个ggplots使用:facet_wrapyx

假设我们有:

library(ggplot2)
library(dplyr)

colnames(mtcars)

mtcars %>% 
  ggplot(aes(hp, mpg)) + 
  geom_point() + 
  geom_smooth(method = "lm")


mtcars %>% 
  ggplot(aes(hp, cyl)) + 
  geom_point() + 
  geom_smooth(method = "lm")

mtcars %>% 
  ggplot(aes(hp, disp)) + 
  geom_point() + 
  geom_smooth(method = "lm")

mtcars %>% 
  ggplot(aes(hp, drat)) + 
  geom_point() + 
  geom_smooth(method = "lm")

.
.
.
mtcars %>% 
  ggplot(aes(hp, carb)) + 
  geom_point() + 
  geom_smooth(method = "lm")

我知道上面的图可以手动创建,然后使用网格排列组合,但是有更有效的方法吗?

标签: rggplot2tidyverse

解决方案


通过一点数据扩充,我们可以做到。我们首先使用 创建一个“id” row_number,然后使用该gather函数从一个宽数据集转到一个高数据集。我们取消选择idhp列。

mtcars %>%
    mutate(id = row_number()) %>%
    gather(variable, value, -id, -hp) %>%
    ggplot(aes(hp, value))+
    geom_point()+
    geom_smooth(method = "lm")+
    facet_wrap(~variable, scales = "free_y")

在此处输入图像描述


推荐阅读