R 为带有图层的ggplot2条形图指定稳定颜色

R 为带有图层的ggplot2条形图指定稳定颜色,r,plot,ggplot2,R,Plot,Ggplot2,我正在寻找一种方法来控制条形图中各部分的颜色,以便在绘制数据子集时保持稳定。 我看到了这个解决方案: 这看起来很有希望,但我似乎无法将其应用于我的数据。我怀疑这与我使用的图层有关 我生成绘图的代码是: plot = ggplot(subdata,mapping = aes(x = as.factor(group))) + layer(geom = "bar", mapping = aes(fill = as.factor(NUM_MOTIFS))) 我可以获取完整数据集

我正在寻找一种方法来控制条形图中各部分的颜色,以便在绘制数据子集时保持稳定。 我看到了这个解决方案:

这看起来很有希望,但我似乎无法将其应用于我的数据。我怀疑这与我使用的图层有关

我生成绘图的代码是:

   plot = ggplot(subdata,mapping = aes(x = as.factor(group))) +
        layer(geom = "bar", mapping = aes(fill = as.factor(NUM_MOTIFS)))
我可以获取完整数据集的级别,但当我尝试将其添加到绘图时,我始终遇到以下错误:

  Error: Aesthetics must either be length one, or the same length as the dataProblems:as.factor(NUM_MOTIFS)
不管我把它放在哪里。。。 有什么想法吗

编辑: 示例数据:

fulldata = data.frame(group = rep("A",10), NUM_MOTIFS = c(0,0,1,1,1,2,2,2,4,5))
subdata = data.frame(group = rep("B",8), NUM_MOTIFS = c(0,0,1,1,2,2,2,2))

非常感谢

我想这就是你需要的:

#dummy data
fulldata = data.frame(group = rep("A",10), NUM_MOTIFS = c(0,0,1,1,1,2,2,2,4,5))
subdata = data.frame(group = rep("B",8), NUM_MOTIFS = c(0,0,1,1,2,2,2,2))

#merge full and subset data for plotting
df <- rbind(fulldata,subdata)
df$NUM_MOTIFS <- as.factor(df$NUM_MOTIFS)

#plot
ggplot(df,aes(group,fill=NUM_MOTIFS)) + geom_bar()
#虚拟数据
fulldata=data.frame(组=rep(“A”,10),NUM_基序=c(0,0,1,1,2,2,4,5))
子数据=数据帧(组=代表(“B”,8),NUM_基序=c(0,0,1,1,2,2,2))
#合并完整数据和子集数据以进行打印

df我认为这会奏效。请注意,您可以为“cbbPalette”(cbbPalette)选择其他值

fulldata=data.frame(group=rep(“A”,10),NUM_motions=c(0,0,1,1,1,2,2,2,4,5))
子数据=数据帧(组=代表(“B”,8),NUM_基序=c(0,0,1,1,2,2,2))
fulldata$NUM_motions=as.factor(as.character(fulldata$NUM_motions))
子数据$NUM_motions=as.factor(as.character(子数据$NUM_motions))
级别(子数据$NUM_基序)=级别(完整数据$NUM_基序)

cbbPalette最好为其他人提供一些示例数据来测试您的代码谢谢,akrun。请看我的编辑谢谢zx8754,但我想把它放在不同的图中(主要是为了得到列之间相同高度的效果)…谢谢,Uri Obolski-这正是我想要的!我一直知道我可以信任互联网:)
fulldata = data.frame(group = rep("A",10), NUM_MOTIFS = c(0,0,1,1,1,2,2,2,4,5))
subdata = data.frame(group = rep("B",8), NUM_MOTIFS = c(0,0,1,1,2,2,2,2))
fulldata$NUM_MOTIFS=as.factor(as.character(fulldata$NUM_MOTIFS))
subdata$NUM_MOTIFS=as.factor(as.character(subdata$NUM_MOTIFS))

levels(subdata$NUM_MOTIFS)=levels(fulldata$NUM_MOTIFS)

cbbPalette <- c("#000000", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7")

ggplot(subdata,mapping = aes(x = as.factor(group),fill=NUM_MOTIFS)) +geom_bar()+
  scale_fill_manual(values=cbbPalette)


ggplot(fulldata,mapping = aes(x = as.factor(group),fill=NUM_MOTIFS)) +geom_bar()+
  scale_fill_manual(values=cbbPalette)