将各个色板分配到不同的因子类别

时间:2015-10-02 16:02:10

标签: r ggplot2

我的数据集由36个“网站”组成,其中12个3个网站是复制三元组。数据集有两个系列“R”和“D”。一些R和D - 三元组相互关联,由字母后面的数字索引表示:因此,R2i和D2i系列属于一起,R3i和D3i等等。扭曲R7i和R1i在D世界中没有相应的东西。 在图中,所有四个网站重复的颜色都不同,但我想平等地对相关组进行着色,以便相关的三角形以相同的颜色显示。

在该示例中,三角形D2和R2应该具有相同的颜色,并且D3 / R3也是如此。

enter image description here

以下是代码:

 sites <- structure(list(Sample = c("R21", "R22", "R23", "R31", "R32", 
"R33", "D21", "D22", "D23", "D31", "D32", "D33"), X = c(-0.00591212751574749, 
0.341048420056647, 0.430793063675178, 0.432479460946573, 0.239326674010454, 
0.202491749301479, -0.951185318446942, -0.596668772966298, -0.939366882995036, 
-0.522651768953026, -0.23338622249853, -0.176826307377661), Y = c(-0.0742136034318636, 
-0.345049510288858, 0.183433103229042, -0.108409938703458, -0.0276483081985604, 
-0.129547387046024, 0.26657938925131, 0.759126587423588, 0.103436047537972, 
-0.178345595609023, -0.116710668776298, -0.0292021298523572), 
    Treatment = c("B", "B", "B", "C", "C", "C", "H", "H", "H", 
    "I", "I", "I"), Group = structure(c(2L, 2L, 2L, 3L, 3L, 3L, 
    2L, 2L, 2L, 3L, 3L, 3L), .Label = c("A", "B", "C", "D", "E", 
    "F", "G"), class = "factor")), .Names = c("Sample", "X", 
"Y", "Treatment", "Group"), row.names = c(4L, 5L, 6L, 7L, 8L, 
9L, 22L, 23L, 24L, 25L, 26L, 27L), class = "data.frame")

library(plyr)
find_hull <- function(df) df[chull(df$X, df$Y), ]
hulls <- ddply(sites , "Treatment", find_hull)

ggplot()+
 geom_point(data=sites, aes(X, Y, col=Treatment), alpha=1,show_guide=FALSE) +
 geom_text(data=sites, aes(X, Y, label=Sample), size=3, show_guide=FALSE) +
 geom_polygon(data = hulls, aes(X, Y, colour=Treatment, fill=Treatment), lty="dashed", alpha = 0.2, show_guide=FALSE) +
 theme_bw()+
 coord_fixed()

Treatment提供网站三元组,Group表示相关组。 数据帧hulls需要Treatment中的因子级别才能正确连接点:如果我将Group传递给颜色参数,则所有点都将被连接。

ggplot()+
  geom_point(data=sites, aes(X, Y, col=Treatment), alpha=1,show_guide=FALSE) +
  geom_text(data=sites, aes(X, Y, label=Sample), size=3, show_guide=FALSE) +
  geom_polygon(data = hulls, aes(X, Y, colour=Group, fill=Group), lty="dashed", alpha = 0.2, show_guide=FALSE) +
  theme_bw()+
  coord_fixed() 

enter image description here

所以我想我是否可以为每个因素分配单独的颜色选择,这样我就可以根据需要为因子水平分配相同的颜色。

感谢您的任何想法,谢谢!

1 个答案:

答案 0 :(得分:1)

你非常接近。解决方案实际上比更改调色板容易一些。您只需要添加group美学。

ggplot() +
  geom_point(data=sites, aes(X, Y, col=Treatment), alpha=1,show_guide=FALSE) +
  geom_text(data=sites, aes(X, Y, label=Sample), size=3, show_guide=FALSE) +
  geom_polygon(data = hulls, aes(X, Y, group = Treatment, colour = Group, fill = Group), 
               lty="dashed", alpha = 0.2, show_guide=FALSE) +
  theme_bw() +
  coord_fixed()

enter image description here