如何在根据 R 中的另一组定位时用不同颜色填充点?

How can I fill dots with different colors while positioning them according to another group in R?

我有一个数据集,其中不同的基因型经历了不同的测试条件。这些是在多个不同的队列中完成的。因此,我想制作一个点图来区分不同的基因型。我还希望每个基因型组中的每个点都有一种颜色,代表它们来自哪个队列。

我创建了一个数据集作为例子:

Y<-c(2,3,1,6,4,5,3,3,4)
X<-c('test','test','test','test','control','control','control','test','control')
Cohort <- c("first", "Second", "Second", "Second", "Second", "first", "Second","Second", "first")
Genotype<-c("WT","WT","WT","Mutant","Mutant","Mutant","Mutant","WT","WT")

DF<-data.frame(X,Y,Cohort,Genotype)
DF

ggplot(DF, aes(x=X, y=Y, group= X:Genotype)) +
  geom_dotplot(binaxis = "y", stackdir = "center", binwidth = 0.5, stroke= 3, aes(colour= Genotype, fill = Cohort), position = position_dodge(1)) +
  scale_fill_manual(values = c("light blue", "blue"))+
  scale_color_manual(values = c("orange",  "purple"))

当我执行这段代码时,我得到了一个与我想要的相似的图表。但是,有些点留空,而不是根据队列进行着色。

Here is the graph with some dots unfilled.

感谢您的帮助!

也许您应该删除 aes 中的 group。 举个例子:

ggplot(DF, aes(x = X, y = Y, fill = Cohort, color = Genotype))+
  geom_point(shape = 21, size = 10, position = position_jitter(0.2), stroke = 2)+
  scale_fill_manual(values = c("light blue", "blue"))+
  scale_color_manual(values = c("orange",  "purple"))+
  guides(fill = guide_legend(override.aes = list(fill = c("light blue", "blue"), color = c(NA,NA))))

它是否回答了您的问题?


编辑:分隔 WT/Mutant Control/Test

如果要根据治疗和基因型分离 x 值,可以使用 interaction 根据治疗和基因型创建 4 个 x 值:

ggplot(DF, aes(x = interaction(X,Genotype), y = Y, fill = Cohort, color = Genotype))+
  geom_point(shape = 21, size = 10, stroke = 2, position = position_dodge2(0.5))+
  scale_fill_manual(values = c("light blue", "blue"))+
  scale_color_manual(values = c("orange",  "purple"))+
  guides(fill = guide_legend(override.aes = list(fill = c("light blue", "blue"), color = c(NA,NA))))

另一种可能性是使用 facet_wrap:

对图形进行分面
ggplot(DF, aes(x = Genotype, y = Y, fill = Cohort, color = Genotype))+
  geom_point(shape = 21, size = 10, stroke = 2, position = position_dodge2(0.5))+
  scale_fill_manual(values = c("light blue", "blue"))+
  scale_color_manual(values = c("orange",  "purple"))+
  guides(fill = guide_legend(override.aes = list(fill = c("light blue", "blue"), color = c(NA,NA))))+
  facet_wrap(~X, strip.position = "bottom")+
  theme(strip.placement = "outside",
        strip.background = element_blank(),
        panel.spacing = unit(-1,"lines"),
        axis.title.x = element_blank())