在ggplot2中为变量定义图例颜色

时间:2017-02-14 16:01:46

标签: r ggplot2 legend-properties

我想要做的是使用不同的样本循环数据集,并使用ggplot2制作叠加密度图。将1个参考样品与其他样品中的一个一起绘制在每个图中。 绘图本身不是问题,但颜色是:

数据集:

df <- data.frame(SampleName = c("a","a","a","b","b","b","c","c","c"),
       Data = c(1,1,2,4,6,7,3,4,9))

使用scale_fill_manual,我可以为特定样本指定颜色:

#1

ggplot() + 
  geom_density(data=subset(df, SampleName == "a"), 
               aes(x = Data, group=SampleName, fill=SampleName), alpha= 0.6) +
  geom_density(data=subset(df, SampleName == "b"), 
               aes(x = Data, group=SampleName, fill=SampleName), alpha= 0.6) +
  scale_fill_manual(values = c("b" = "red", "a" = "green"))

使用包含所有样品名称的载体,我可以制作一个循环,用“b”作为固定样品绘制所有叠加图:

#2

Samples <- c("a","b","c")

for(i in 1:length(Samples)){
print(ggplot() + 
            geom_density(data=subset(df, SampleName == Samples[i]), 
                         aes(x = Data, group=SampleName, fill=SampleName), alpha= 0.6) +
            geom_density(data=subset(df, SampleName == "b"), 
                         aes(x = Data, group=SampleName, fill=SampleName), alpha= 0.6) +
            scale_fill_manual(values = c("red", "green"))
  )
}

#2中的问题是当b固定时样本会改变颜色 - &gt;在第一个图中,b是绿色,a是红色,在图3b中是红色,c是绿色。 当我尝试将#1中的颜色分配给特定样本时(请参阅#3),将显示以下错误消息:

“错误:意外'='in: “aes(x = Data,group = SampleName,fill = SampleName),alpha = 0.6))+           scale_fill_manual(values = c(“b”=“red”,Samples [i] =“

我尝试了不同的东西,使用'。字符,粘贴(),'样本[i] =“绿色”'更多'文字',但这似乎不起作用。 任何解决方案?

#3

for(i in 1:length(Samples)){
  print(ggplot() + 
      geom_density(data=subset(df, SampleName == Samples[i]), 
                   aes(x = Data, group=SampleName, fill=SampleName), alpha= 0.6) +
      geom_density(data=subset(df, SampleName == "b"), 
                   aes(x = Data, group=SampleName, fill=SampleName), alpha= 0.6)) +
      scale_fill_manual(values = c("b" = "red", Samples[i] = "green"))
}

1 个答案:

答案 0 :(得分:0)

您可以使用setNames轻松创建命名向量,您可以在其中使用需要评估的表达式。例如:

setNames(c('red', 'green'), c('b', Samples[i]))

这使得:

for(i in 1:length(Samples)){
  print(ggplot() + 
      geom_density(data=subset(df, SampleName == Samples[i]), 
                   aes(x = Data, group=SampleName, fill=SampleName), alpha= 0.6) +
      geom_density(data=subset(df, SampleName == "b"), 
                   aes(x = Data, group=SampleName, fill=SampleName), alpha= 0.6)) +
      scale_fill_manual(values = setNames(c('red', 'green'), c('b', Samples[i])))
}