ggbiplot:更改磅值后如何维护组颜色?

时间:2015-06-21 19:38:14

标签: r ggplot2 ggbiplot

我在2种栖息地类型的地块上进行PCA,其中我收集了多个环境变量的数据。我能够从ggbiplot默认值更改点的颜色。我希望每个点的大小取决于该图中的冠层覆盖,我能够通过以下方式实现:

point.size = df$canopy.cover * 0.1  

其中df$canopy.cover值的范围为0-100和0.1,因为100%的冠层覆盖=点大小为10.

问题:在改变点的大小后,我无法保持与两组相关的颜色。使用以下伪数据:

env.vars<-data.frame(replicate(5,sample(0:10,20,rep=TRUE)))

cover<-c(89, 92, 72, 53, 88, 89, 71, 83, 71, 66, 23, 30,  5, 15, 57, 54,0, 23, 9, 16)

habitat<-c("habitat1", "habitat2", "habitat1", "habitat2", "habitat1", "habitat2", "habitat1", "habitat2", "habitat1", "habitat2", "habitat1", "habitat2", "habitat1", "habitat2", "habitat1", "habitat2", "habitat1", "habitat2", "habitat1", "habitat2")

point.size<-cover*0.1

nest.env.pca <- prcomp(env.vars, center = TRUE, scale. = TRUE) 

g <- ggbiplot(nest.env.pca, obs.scale = 1, var.scale = 1, 
     group = habitat, ellipse = TRUE, 
     circle = TRUE, varname.size=3)+
     scale_colour_manual(values=c("blue", "red")) +
     geom_point(size=point.size)

print(g)

我得到类似的东西:

enter image description here

当我替换:

geom_point(size=point.size)

使用:

geom_point(aes(colour=habitat), size=point.size)

根据ggbiplot - change the point size我收到以下错误:

Error: Incompatible lengths for set aesthetics: size

有什么建议吗?感谢。

编辑:一些PseudoData尝试使用:

1 个答案:

答案 0 :(得分:1)

我认为这是一个一般的ggplot2语法问题,因为它出现在更简单的示例中(例如,ggplot(mtcars) + geom_point(aes(disp, hp, color=cyl), size =mtcars$model)

但是,我认为这对你有用:

geom_point(aes(X1, X2, color=habitat, size = point.size)) + scale_size_identity()

因此问题代码的完整答案是(来自Emilio的评论):

env.vars<-data.frame(replicate(5,sample(0:10,20,rep=TRUE)))

cover<-c(89, 92, 72, 53, 88, 89, 71, 83, 71, 66, 23, 30,  5, 15, 57, 54,0, 23, 9, 16)

habitat<-c("habitat1", "habitat2", "habitat1", "habitat2", "habitat1", "habitat2", "habitat1", "habitat2", "habitat1", "habitat2", "habitat1", "habitat2", "habitat1", "habitat2", "habitat1", "habitat2", "habitat1", "habitat2", "habitat1", "habitat2")

point.size<-cover*0.1

nest.env.pca <- prcomp(env.vars, center = TRUE, scale. = TRUE) 

g <- ggbiplot(nest.env.pca, obs.scale = 1, var.scale = 1, 
     group = habitat, ellipse = TRUE, 
     circle = TRUE, varname.size=3)+
     scale_colour_manual(values=c("blue", "red")) +
     geom_point(aes(color=habitat, size = point.size)) + scale_size_identity() 

print(g)