【问题标题】:Use different colors/shapes for scatterplot with two groups in R在 R 中使用不同颜色/形状的散点图与两组
【发布时间】:2017-05-08 09:26:43
【问题描述】:

我目前正在使用 R 中的 lattice 包创建散点图矩阵,使用 splom 函数。我的数据集有两个组,标记在两个不同的列中,如下所示:

PC1 PC2 PC3 Group1 Group2
1   2   3   A      X
1   2   3   B      X
1   2   3   C      X
1   2   3   D      X
1   2   3   A      Y
1   2   3   B      Y
1   2   3   C      Y
1   2   3   D      Y
1   2   3   A      Z
1   2   3   B      Z
1   2   3   C      Z
1   2   3   D      Z

我可以让 splom 函数为其中一组使用不同的颜色和形状,但不能同时使用以下代码:

splom(~pcVT[,1:3], data = pcVT, xlab = NULL, groups = Group1, pch = c(1,2,3),
col = super.sym$col[1:3], panel = panel.superpose, 
key = list(points = list(pch = c(1,2,3),col = super.sym$col[1:3]),text = list(mylabels)))

我怎样才能让它使用两个组进行着色和形状 - 即,我希望 Group1 基于颜色绘制,Group2 根据形状绘制。或者,如果 splom 不能做到这一点,有没有使用 gpplot2 的好方法?

非常感谢!

【问题讨论】:

    标签: r matrix scatter-plot lattice


    【解决方案1】:

    您的示例不可重现,您的数据集也不是很有用。 我又做了一个……

    这是一个带有底图的解决方案:

    d <- as.data.frame(princomp(iris[,1:4])$scores)
    d$Group1 <- iris$Species
    d$Group2 <- factor(sample(c("A","B","C"), 150, replace = TRUE))
    
    mycols <- c("forestgreen", "gold", "dodgerblue")
    
    x11(width = 16/2.54, height = 12/2.54)
    pairs(d[,1:4], oma=c(3,3,6,3), 
          col = mycols[as.numeric(d$Group1)], pch = c(1:3)[as.numeric(d$Group2)], gap = 0)
    legend("top", col = mycols, legend = levels(d$Group1), pch = 20, 
           xpd = NA, ncol = 3, bty = "n", inset = 0.01, pt.cex = 1.5)
    legend("top", pch = 1:3, legend = levels(d$Group2), col = "black",
           xpd = NA, ncol = 3, bty = "n", inset = -0.03)
    

    如果您想要 ggplot 解决方案,请探索GGally:ggpairs 的可能性(计算速度要慢得多):

    library(GGally)
    ggpairs(data=d, mapping = aes(color = Group1, shape = Group2), 
            columns = 1:4, legend = c(2,1))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 2016-04-07
      • 1970-01-01
      • 1970-01-01
      • 2016-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多