You need to enable JavaScript to run this app. R语言按数据列因子给散点图着色 鸢尾花散点矩阵仅显白圈问题
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 23:15:03