首页 > 解决方案 > 如何在根据 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"))

当我执行这段代码时,我得到一个类似于所需的图表。但是,有些点是空白的,而不是根据队列着色。

这是一些未填充的点的图表。

谢谢您的帮助!

标签: rggplot2groupingfill

解决方案


也许你应该删除group你的aes. 在这里,一个例子:

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/突变控制/测试

如果要根据治疗和基因型分离 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())

在此处输入图像描述


推荐阅读