ggplot中的两个填充变量

时间:2015-04-03 09:47:58

标签: r ggplot2


我想创建一个ggplot,它使用两个变量以不同的方式填充。基于此solution我做了

x = c("Band 1", "Band 2", "Band 3")
y1 = c("1","2","3")
y2 = c("2","3","4")

to_plot <- data.frame(x=x,y1=y1,y2=y2)
melted<-melt(to_plot, id="x")

ggplot(melted,aes(x=x,y=value,fill=variable)) + 
        geom_bar(stat="identity",position = "identity", alpha=.3)

enter image description here

但不是alpha参数,我想以不同的方式为每个Band值着色,并将y1实现为白色条,边框的颜色为给定{{ 1}}和Band为条形,颜色为给定y2。怎么做?

1 个答案:

答案 0 :(得分:5)

这是我最好的尝试。你需要几个覆盖,因为你的情节不是“ggplot-canonical”w.r.t.到aes映射。

# extra variable to map to fill
melted$col <- ifelse(melted$variable == "y1", "white", melted$x)
# reorder appearance, so that y1 is plotted after y2
melted <- with(melted, melted[order(-as.numeric(variable)), ])

ggplot(melted, aes(x=x, y=value, fill=col, color=x, alpha=variable)) + 
  geom_bar(stat="identity", position="identity", size=2) + 
  scale_fill_manual(values = c("red", "green", "blue", "white"), guide=FALSE) + 
  scale_color_manual(values = c("red", "green", "blue")) + 
  scale_alpha_manual(values = c(1, 0.5), guide=FALSE)

enter image description here