这是问题所在,我想仅使用R基本功能制作一个情节。我们的想法是制作一个散点图,其中每个点代表一个国家。该数据集每隔一段时间更新一次,并非每次所有国家都存在。
我想定义每个国家/地区获得的颜色。到目前为止,我可以使用一些嵌套的ifelse语句来做到这一点。但是,如果您运行以下示例几次,您将看到颜色并不总是与定义的颜色相对应。我试图解决它,但我根本无法解决它。我确定这是愚蠢的事,但目前我无法解决这个问题。
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")
提前感谢所有帮助。
Patrao
答案 0 :(得分:3)
通过将颜色添加到不同的data.frame,您可以轻松访问它们而不使用ifelse:
dat <- data.frame(Country=sample(c("Scotland","Sweeden","Ireland","Netherlands"),
10,replace=T),x =sample( 1:10,10),y= sample( 1:10,10))
colorFrame <- data.frame(Country=c("Scotland","Sweeden","Ireland","Netherlands","France"),
Color = c("darkblue","yellow","green","orange","red"))
dat <- merge(dat,colorFrame)
plot(dat$x,dat$y,pch=20,cex=2,col=as.vector(dat$Color))
legend("bottomleft",legend=colorFrame[which(colorFrame$Country %in% unique(dat$Country)),]$Country,col=as.vector(colorFrame[which(colorFrame$Country %in% unique(dat$Country)),]$Color),pch=20,cex=1, bty = "n")