在 n 个图中针对 n 个数值变量绘制一个数值变量 [英] Plot one numeric variable against n numeric variables in n plots
问题描述
我有一个巨大的数据框,我想绘制一些图来了解不同变量之间的关联.我无法使用
I have a huge data frame and I would like to make some plots to get an idea of the associations among different variables. I cannot use
pairs(data)
,因为那会给我 400 多个图.但是,有一个响应变量 y 我特别感兴趣.因此,我想针对所有变量绘制 y,这会将绘图数量从 n^2 减少到 n.我该怎么做?
, because that would give me 400+ plots. However, there's one response variable y I'm particularly interested in. Thus, I'd like to plot y against all variables, which would reduce the number of plots from n^2 to n. How can I do it?
为了清楚起见,我添加了一个示例.假设我有数据框
I add an example for the sake of clarity. Let's say I have the dataframe
foo=data.frame(x1=1:10,x2=seq(0.1,1,0.1),x3=-7:2,x4=runif(10,0,1))
我的响应变量是 x3.然后我想生成排成一行的四个图,分别是 x1 vs x3、x2 vs x3、x3 的直方图,最后是 x4 vs x3.我知道如何制作每个情节
and my response variable is x3. Then I'd like to generate four plots arranged in a row, respectively x1 vs x3, x2 vs x3, an histogram of x3 and finally x4 vs x3. I know how to make each plot
plot(foo$x1,foo$x3)
plot(foo$x2,foo$x3)
hist(foo$x3)
plot(foo$x4,foo$x3)
但是我不知道如何将它们排成一排.此外,如果有一种方法可以自动制作所有 n 个图,而不必每次都调用命令 plot(或 hist),那就太好了.当 n=4 时,这不是什么大问题,但我通常处理 n=20+ 个变量,所以它可能是一个拖累.
However I have no idea how to arrange them in a row. Also, it would be great if there was a way to automatically make all the n plots, without having to call the command plot (or hist) each time. When n=4, it's not that big of an issue, but I usually deal with n=20+ variables, so it can be a drag.
推荐答案
Could do reshape2
/ggplot2
/gridExtra
包组合.这样你就不需要指定图的数量.此代码将适用于任意数量的解释变量,无需任何修改
Could do reshape2
/ggplot2
/gridExtra
packages combination. This way you don't need to specify the number of plots. This code will work on any number of explaining variables without any modifications
foo <- data.frame(x1=1:10,x2=seq(0.1,1,0.1),x3=-7:2,x4=runif(10,0,1))
library(reshape2)
foo2 <- melt(foo, "x3")
library(ggplot2)
p1 <- ggplot(foo2, aes(value, x3)) + geom_point() + facet_grid(.~variable)
p2 <- ggplot(foo, aes(x = x3)) + geom_histogram()
library(gridExtra)
grid.arrange(p1, p2, ncol=2)
这篇关于在 n 个图中针对 n 个数值变量绘制一个数值变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!