r:针对每一列绘制每一列

r: Plotting each column against each column

我有一个包含 7 列(2 个因子,5 个数字)的数据框 ("data")。第一列包含 7 个不同国家的名称,在接下来的列中,我收集了代表每个国家的不同参数(如人口、GDP 等)的数据。在最后一列中,一个因子变量指定了各个国家属于哪个大陆。

数据如下所示:

structure(list(Country = structure(c(5L, 4L, 7L, 2L, 1L, 6L, 
3L), .Label = c("Brazil", "Chile", "China", "France", "Germany", 
"India", "Netherlands"), class = "factor"), GDP = c(0.46, 0.57, 
0.75, 0.56, 0.28, 0.88, 1), Population = c(0.18, 0.09, 0.54, 
0.01, 0.02, 0.17, 0.84), Birth.rate = c(87.21, 18.34, 63.91, 
14.21, 5.38, 51.19, 209.26), Income = c(43.89, 18.23, 63.91, 
12.3, 0.1, 14.61, 160.82), Savings = c(43.32, 0.11, 0, 1.91, 
5.29, 36.58, 50.38), Continent = structure(c(2L, 2L, 2L, 3L, 
3L, 1L, 1L), .Label = c("Asia", "Europe", "South America"), class = "factor")), .Names = c("Country", 
"GDP", "Population", "Birth.rate", "Income", "Savings", "Continent"
), class = "data.frame", row.names = c(NA, -7L))

我需要某种循环函数来绘制(例如散点图)每一列,以便最后每一列(除了第一列和最后一列,即两个因子变量)都被绘制出来所有其他列,但每个列都在 单图图表 中(并非所有图都在一个图中)。最好将所有这些图都保存到我本地机器上的某个文件夹中。

另外,如果 x 轴和 y 轴已经根据彼此绘制的相应两列进行了标记,那就太好了。此外,在绘图中的每个点旁边都有一个标签显示各自的国家名称会很方便。最后,根据三个不同的大陆,国家的点可以有三种不同的颜色。

到目前为止我只有一段代码是这样的

for (i in seq(1,length(data),1)) {
   plot(data[,i], ylab=names(data[i]), xlab="Country", 
   text(i, labels=Country, pos=4, cex =.5)) 
} 

如您所见,它仅针对第一列 ("Country") 绘制每一列,这最终不是我想要的。

你知道我是怎么做到的吗?谢谢!

我一直认为包 'lattice' 中的 splom 函数对于这种探索性分析非常有用。这显然不是一个很好的例子,因为它掩盖了组成员资格,但它以 "pairs" 格式显示了点和非参数回归线的组合:

png()
    print( splom(~iris[1:4], groups = Species, data = iris,
          panel = function(x, y, i, j, ...) {
          panel.points(x,y, ...)
          panel.loess(x,y, ...)
      })); dev.off()

您可以直接从 R 使用 pairs()。请注意,dt 代表您的数据集。

pairs(dt)

dt <- structure(list(Country = structure(c(5L, 4L, 7L, 2L, 1L, 6L, 
3L), .Label = c("Brazil", "Chile", "China", "France", "Germany", 
"India", "Netherlands"), class = "factor"), GDP = c(0.46, 0.57, 
0.75, 0.56, 0.28, 0.88, 1), Population = c(0.18, 0.09, 0.54, 
0.01, 0.02, 0.17, 0.84), Birth.rate = c(87.21, 18.34, 63.91, 
14.21, 5.38, 51.19, 209.26), Income = c(43.89, 18.23, 63.91, 
12.3, 0.1, 14.61, 160.82), Savings = c(43.32, 0.11, 0, 1.91, 
5.29, 36.58, 50.38), Continent = structure(c(2L, 2L, 2L, 3L, 
3L, 1L, 1L), .Label = c("Asia", "Europe", "South America"), class =      "factor")), .Names = c("Country",  
"GDP", "Population", "Birth.rate", "Income", "Savings", "Continent"
), class = "data.frame", row.names = c(NA, -7L))