我想创建一个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)
但不是alpha
参数,我想以不同的方式为每个Band
值着色,并将y1
实现为白色条,边框的颜色为给定{{ 1}}和Band
为条形,颜色为给定y2
。怎么做?
答案 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)