使用不同的颜色/形状散点图与R中的两组R
问题描述:
我目前使用R中的网格包来创建散点图矩阵,使用splom函数。我的数据集中有两个组,标记在两个不同的列,如这样:使用不同的颜色/形状散点图与R中的两组R
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)))
我怎么能得到它使用了两组进行着色和形状 - 即,我想组别1根据颜色来绘制,并且第2组基于形状绘制。另外,如果splom不能做到这一点,是否有一种很好的方式来使用gpplot2来做到这一点?
非常感谢!
答
您的示例不可重现,您的数据集不太可用。 我做了一个又一个......
这里是垒积的解决方案:
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))