On Jun 20, 2014, at 9:18 AM, Bea GD wrote:
> I've tried several things but I don't manage to get this plot
right. Any help greatly appreciated!
> I'm running a for loop to produce 4 plots at once. Each plot should
only show data points for a specific group (i.e. 4 plots for groups 1 to 4). The
coordinates of the points should be petal length and width. The colour of these
points should codify the species variable. Finally I'd like to show a legend
for the colours on these plots. It's important that each species has a
unique colour. Thanks you a lot for your input!
>
> # Data
> dd <- iris
>
> dd$group <- ifelse(dd$Sepal.Length>=4.3 &
dd$Sepal.Length<5.2, 1,
> ifelse(dd$Sepal.Length>=5.2 &
dd$Sepal.Length<6.1, 2,
> ifelse(dd$Sepal.Length>=6.1 &
dd$Sepal.Length<7, 3,
> ifelse(dd$Sepal.Length>=7, 4,
NA))))
> dd$group <- as.integer(dd$group)
>
> dd$Species <- c(rep("Wild", 12), rep("Pinky",
12), rep("Orangy", 12), rep("Smelly", 12),
> rep("Pretty", 12), rep("Blue", 12),
rep("Big", 12), rep("Rare", 12),
> rep("Toxic", 12), rep("Danger", 12),
rep("Abundant", 18), rep("Last", 12))
>
>
> # Code to plot 4 graphs. It doesn't work!
> pdf("plot_test.pdf", width=10, height=10)
> par(mfrow=c(2, 2))
> for(b in unique(dd$group)){
> idx <- dd$group==b
> plot(dd$Petal.Length, dd$Petal.Width, ty="n",
xlim=range(dd$Petal.Length), ylim=range(dd$Petal.Width))
> cols <- as.numeric(unique(dd$Species))
> points(dd$Petal.Length[idx], dd$Petal.Width[idx],
> col=cols[as.numeric(dd$Species[idx])])
> legend("right", legend=unique(dd$Species[idx]), pch=1,
col=cols[as.numeric(unique(dd$Species[idx]))])
> }
> dev.off()
This appears to be a duplicate of
http://stackoverflow.com/questions/24333076/for-loop-to-produce-plots-with-legend
and is already answered. You are requesten not to corss-post to SO and Rhelp.
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
--
David Winsemius
Alameda, CA, USA