r - 一个因变量和多个独立变量的 ggplot
问题描述
当变量总是相同并且只是改变变量时,是否可以创建多个ggplots
使用:facet_wrap
y
x
假设我们有:
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")
我知道上面的图可以手动创建,然后使用网格排列组合,但是有更有效的方法吗?
解决方案
通过一点数据扩充,我们可以做到。我们首先使用 创建一个“id” row_number
,然后使用该gather
函数从一个宽数据集转到一个高数据集。我们取消选择id
和hp
列。
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")
推荐阅读
- apache - 防止 apache2 / http2 作为 Docker 容器的守护进程运行?
- javascript - 需要帮助使用 js 将 rel 添加到 img 标签
- anypoint-studio - 如果值满足特定条件,如何仅包含键
- javascript - 可以传递给 Puppeteer page.goto(url) 函数的 URL 字符串中的最大字符数是多少
- python - 无法从 pymodbus 导入 BinaryPayloadBuilder
- asp.net-core - 对大型 Blazor 应用程序进行小改动
- php - 我以一对一的关系加入了两个表(策略和车辆)。我想从 vehicle.policy 为空的车辆获取记录
- python - 如何从 python 读取这个二进制文件,并提供二进制文件、文本文件和代码?
- azure-data-factory - 如何在不使用参数的情况下获取子管道内父管道的触发器名称
- html - CSS 电话铃声动画