在ggplot中如何填充两个变量?

3


我想创建一个使用两个变量以不同方式填充的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)

enter image description here

但是我想要用不同的颜色为每个Band值上色,同时将y1变成带有给定Band颜色边框的白色条形图,将y2变成给定Band颜色的条形图。如何实现?

1个回答

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)

enter image description here


1
有些繁琐,但我想这就是预期的结果! - Colonel Beauvel
@tonytonov 还有一件事。当您添加 scale_alpha_manual(values = c(1, 0.5)) 而没有 guide = F 时,您会在图例中得到黑色矩形和灰色矩形。如何将灰色更改为白色? - Nicolabo
1
@Nicolabo https://dev59.com/IWQo5IYBdhLWcg3wDb0J - tonytonov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接