mercredi 9 septembre 2015

Plot legend using nested ifelse

Here’s the problem, I would like to make a plot using only the R basic functions. The idea is to make a scatterplot where each point represents a country. This data set is updated every so often and not all countries are present every time.

I want to define the colours that each country gets. So far so good I can do this using some nested ifelse statements. However ,if you run the example below a few times you’ll see that the colours not always correspond to what was defined. I’ve tried to sort it out but I simply can’t fix it. I’m sure it is something silly but at the moment I can’t work it out.

  dat <- data.frame(Country=sample(c("Scotland","Sweeden","Ireland","Netherlands"),
10,replace=T),x =sample( 1:10,10),y= sample( 1:10,10))

plot(dat$x,dat$y,pch=20,cex=2,col=ifelse(dat$Country=="Scotland","darkblue",
ifelse(dat$Country=="Netherlands","orange",ifelse(dat$Country=="Ireland","green",
ifelse(dat$Country=="France","red",ifelse(dat$Country=="Sweeden","yellow","Black"))))))

legend("bottomleft",legend=unique(dat$Country),col=ifelse(dat$Country=="Scotland",
"darkblue",ifelse(dat$Country=="Netherlands","orange",ifelse(dat$Country=="Ireland",
"green",ifelse(dat$Country=="France","red",ifelse(dat$Country=="Sweeden","yellow",
"Black"))))),pch=20,cex=1, bty = "n")

Thanks in advance for all the help.

Patrao

Aucun commentaire:

Enregistrer un commentaire