ggplot中的两个填充变量

Nic*_*abo 3 r ggplot2


我想创建一个ggplot使用两个变量来填充不同的方式.基于这个解决方案我做了

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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

但不是alpha参数,我想每个颜色Band以不同的方式和价值实现y1的颜色与边框的白色柱状给定的Band,并y2作为与给定的彩条Band.怎么做?

ton*_*nov 5

这是我最好的尝试.你需要在这里和那里进行几次覆盖,因为你的情节不是aes映射的"ggplot-canonical" .

# 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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述