Reputation: 4873
I looked in the internet and also in this website but I didn't found a solution, so sorry if my question has already been answered. I have a dataframe in which several rows have the same ID. Let's say for example
ID Value1 Value2
P1 12 3
P1 15 4
P22 9 12
P22 15 14
P22 13 9
P30 10 12
Is it possible to write a script that take the dataframe and plots in different pages Value1~Value2, for every different ID? In other words I'd have 3 plots, in which value1 is plotted versus value2 for P1, P22 and P30.
I try to write a script with a loop (but I'm a really newby of R):
for (i in levels(dataset$ID)) {
plot(dataset[i,2], dataset[i,2])
}
But I receive the errors:
Errore in plot.new() : figure margins too large
Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf
Upvotes: 1
Views: 2397
Reputation: 121568
I would use by
here , to group your data by ID. Note Also that I use the ID for the title. If you'don't have a lot of ID , maybe a facet approach , suing a more high level plot package, as shown by @Roman is better here.
by (dataset,dataset$ID,function(i){
plot(i$Value1,i$Value1,main=unique(i$ID))
})
Note also this don't deal with you "Errore" ( I guess Spanish for Error )
Errore in plot.new() : figure margins too large
Generally When I get this error, with RStudio, I enlarge my plot region. Otherwise you can always set your plot margin using something like , before the call to the plot loop:
par(mar=rep(2,4))
Upvotes: 4
Reputation: 132706
It's not clear to me what you mean by "in different pages". Pages of a PDF? Then run the code in the comments too.
DF <- read.table(text="ID Value1 Value2
P1 12 3
P1 15 4
P22 9 12
P22 15 14
P22 13 9
P30 10 12",header=TRUE)
#pdf("myplots.pdf")
for (i in levels(DF$ID)) {
plot(Value1 ~ Value2,data=DF[DF$ID==i,])
}
#dev.off()
Upvotes: 2
Reputation: 70643
I would do it like this.
mydf <- data.frame(id = sample(1:4, 50, replace = TRUE), var1 = runif(50), var2 = rnorm(50))
library(ggplot2)
ggplot(mydf, aes(x = var1, y = var2)) +
theme_bw() +
geom_point() +
facet_wrap(~ id)
Upvotes: 2