Rのサンプルデータセットirisの、萼の長さ(Length)と幅(Width)の関係を種ごとに凡例の色と形を変えてプロットする。
sanpuz.R
attach(iris)
plot(x=NULL, xlim=c(4,8), ylim=c(0,6), cex=1.2, cex.axis=1.5, las=1, xlab="Sepal Length", ylab="Sepal Width", cex.lab=1)
points(Sepal.Length[Species=="setosa"], Sepal.Width[Species=="setosa"], cex=1.3)
points(Sepal.Length[Species=="versicolor"], Sepal.Width[Species=="versicolor"], pch=2, cex=1.3, col=2)
points(Sepal.Length[Species=="virginica"], Sepal.Width[Species=="virginica"], pch=0, cex=1.3, col=3)
legend("topleft", legend=c("setosa", "versicolor", "virginica"), bty="n", pch=c(1,2,0), col=1:3, cex=1.4)
これまで重描きをするときは
plot()
par(new=T)
plot()
...
と書いていたのですが、絶対にpoints()を使ったほうがいいですね。
回帰直線も描くなら、
sanpuz.R
attach(iris)
plot(x=NULL, xlim=c(4,8), ylim=c(0,6), cex=1.2, cex.axis=1.5, las=1, xlab="Sepal Length", ylab="Sepal Width", cex.lab=1)
points(Sepal.Length[Species=="setosa"], Sepal.Width[Species=="setosa"], cex=1.3)
points(Sepal.Length[Species=="versicolor"], Sepal.Width[Species=="versicolor"], pch=2, cex=1.3, col=2)
points(Sepal.Length[Species=="virginica"], Sepal.Width[Species=="virginica"], pch=0, cex=1.3, col=3)
abline(lm(Sepal.Width[Species=="setosa"] ~ Sepal.Length[Species=="setosa"]))
abline(lm(Sepal.Width[Species=="versicolor"] ~ Sepal.Length[Species=="versicolor"]), col=2)
abline(lm(Sepal.Width[Species=="virginica"] ~ Sepal.Length[Species=="virginica"]),col=3)
legend("topleft", legend=c("setosa", "versicolor", "virginica"), bty="n", pch=c(1,2,0), col=1:3, cex=1.4)