R语言按数据列因子给散点图着色 鸢尾花散点矩阵仅显白圈问题
R语言iris数据集散点矩阵着色异常解决办法
问题根源
pairs()函数的顶层bg参数不会自动传递给内部绘制散点的默认面板函数,你写在pairs()括号内的bg配置未生效,因此所有散点默认使用白色填充,而图例显式指定了pt.bg参数所以颜色显示正常- 代码中使用的
mapvalues()函数来自plyr扩展包,若未提前加载该包会导致species列重命名失败,也会干扰颜色索引逻辑
修正后的完整代码
# 先加载依赖包 library(plyr) iris.uci <- read.csv(url("http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"), header=FALSE, col.names =c("sepal.length", "sepal.width", "petal.length", "petal.width","species") ) iris.uci[35,4] = 0.2 iris.uci[38,2:3]= c(3.6, 1.4) iris.uci$species <- mapvalues(iris.uci$species, from = c("Iris-setosa", "Iris-versicolor", "Iris-virginica"), to = c("setosa", "versicolor", "virginica")) # 自定义面板函数传递bg参数 pairs(iris.uci[,1:4], lower.panel=NULL, cex=2, cex.labels =2, panel = function(x,y,...){ points(x,y, pch=21, bg = c("black", "grey", "white")[as.integer(iris.uci$species)]) }) par(xpd=NA) legend("bottomleft", inset=c(-.5,0), legend=c("setosa", "versicolor", "virginica"), pch=21, pt.bg=c("black", "grey", "white"), pt.cex =2, y.intersp=1, cex=1.5, bty="n" )
额外说明
你原代码中重命名物种时将virginica拼写为verginica,上述代码已修正该笔误,不影响功能但建议保持标准命名。
内容的提问来源于stack exchange,提问作者Mike Cashin
相关产品推荐
相关产品推荐

