显示ggplot图例中的所有因子级别

时间:2016-06-08 17:47:17

标签: r ggplot2 legend

我想创建一个ggplot,其中所有因子水平都显示在图的图例中,即使并非所有因子都在数据中。让我说明我的意思。

这是我的数据:

set.seed(1)
df <- data.frame(y.tick.lab = letters[1:10],p.value=c(runif(6,0,0.25),runif(4,0.25,1)),
                 group=c(rep("enriched",3), rep("depleted",3), rep("enriched",2), rep("depleted",2)),
                 bar.col=rep("#C8C8C8",10), p.value.cat=rep("I",10),
                 stringsAsFactors = FALSE)
df$log.p.value = -10*log10(df$p.value)

现在我根据bar.col更新p.value.catp.value

p.val2col.df = data.frame(col = c("#2f3b61","#0000B2","#436CE8","#9494FF","#E0E0FF","#7d4343","#B20000","#C74747","#E09898","#EBCCD6"),
                          p.value = rep(c(0.05,0.1,0.15,0.2,0.25),2),
                          cat = c("D(0-0.05]","D(0.05-0.1]","D(0.1-0.15]","D(0.15-0.2]","D(0.2-0.25]","E(0-0.05]","E(0.05-0.1]","E(0.1-0.15]","E(0.15-0.2]","E(0.2-0.25]"),
                          group = c(rep("depleted",5),rep("enriched",5)), stringsAsFactors = F)
idx = which(df$p.value < 0.25)
df$bar.col[idx] = sapply(1:length(idx), function(x) {
  p.val2col.df$col[min(which(p.val2col.df$group == df$group[idx[x]] & p.val2col.df$p.value > df$p.value[idx[x]]))]
})
df$p.value.cat[idx] = sapply(1:length(idx), function(x) {
  p.val2col.df$cat[min(which(p.val2col.df$group == df$group[idx[x]] & p.val2col.df$p.value > df$p.value[idx[x]]))]
})

我在这里设置bar.col的级别,以包含p.val2col.df中的所有内容:

color.order = c(p.val2col.df$col[1:5],"#C8C8C8", p.val2col.df$col[10:6])
color.labels = c(p.val2col.df$cat[1:5],"I(0.25-1]", p.val2col.df$cat[10:6])
names(color.order) = color.labels
df$bar.col = factor(df$bar.col, levels=color.order, labels=color.labels)

这是我的ggplot代码:

 pl = ggplot(df, aes(y=log.p.value, x=y.tick.lab,fill=bar.col)) +
 scale_fill_manual(values=color.order, name="E/D(P-value range)") +
 geom_bar(stat="identity", width=0.2) + 
 scale_y_continuous(limits=c(0,30), labels = c(seq(0,20,10),"   >30"),expand=c(0,0)) +
 theme(axis.text=element_text(size=8), axis.title=element_text(size=8,face="bold")) +  
 coord_flip() + 
 theme(plot.margin=unit(c(0.1,1,0.1,0.1),"cm"), axis.title.y = element_text(size=8), axis.title.x = element_text(size=8)) +  
 labs(y="-10log10(P-value)", x="Group")

但生成的图例只包含bar.col而不是df

中的levels(df$bar.col).levels(df$bar.col)

enter image description here

所以我的问题是如何将所有{{1}}传递给传奇?

0 个答案:

没有答案