在R中使用循环的多个图 [英] Multiple plots using loops in R

查看:82
本文介绍了在R中使用循环的多个图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍在尝试使用循环在R中绘图.我想根据以下数据框中的不同名称在下面的数据框中针对z_2绘制z_1列(可视化数据的任何图表).列x_1.

I'm still trying to get my head around using loops to plot in R. I would like to plot (any plot to visualise the data will do) columns z_1 against z_2 in the data frame below according to the different names in column x_1.

x_1 <- c("A1", "A1","A1", "B10", "B10", "B10","B10", "C100", "C100", "C100")


z_1 <- rnorm(10, 70) 

z_2 <- rnorm(10, 1.7)

A <- data.frame(x_1, z_1, z_2)

因此,我想以三种不同的情节结束.一个用于类别A1,一个用于B10,另一个用于C100.我可以使用三个不同的代码来执行此操作,但我希望能够使用循环或任何其他单个代码在同一页面上执行所有三个绘图.实际上,我有一个很大的数据集(4,000行),并且想在一个页面上绘制几个ID(比如说在页面上5个).

As such, I would like to end up with three different plots; one for category A1, one for B10 and another for C100. I can do this using three different codes but I would like to be able to use a loop or any other single code to execute all three plots on the same page. In reality, I have a large dataset (4,000 rows) and would like to plot a couple of IDs on a page (say 5 on a page).

我希望这是有道理的.谢谢你的帮助.

I hope this makes sense. Thanks for your help.

这是我尝试单独绘制它们的地方:

Here's my attempt at plotting them individually:

对于A1:

data_A1 <- A[which(A$x_1 == "A1"), ]
plot(data_A1$z_2, data_A1$z_1)

我也尝试过类似的操作,但收到错误消息

I also tried something like this but getting error messages

for ( i in A$x_1[[i]]){

plot(A[which(A$x_1==A$x_1[[i]]), ], aspect = 1)
}

推荐答案

使用循环的简单方法是

for (cat in unique(x_1)){
  d <- subset(A, x_1 == cat)
  plot(d$z_1, d$z_2)
}

unique(x_1)为您提供x_1的所有唯一值.然后,为每个值获取一个对应的子集,并使用该子集进行绘图.

unique(x_1) gets you all the unique values of x_1. Then, for each of these values get a corresponding subset and use this subset for plotting.

这篇关于在R中使用循环的多个图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆