在ggplot2中叠加条形图

Har*_*pal 11 r ggplot2

我正试图覆盖条形图 ggplot2

我当前的代码生成条形图,但它们堆叠在一起.我不想要这个,我希望它们叠加,所以我可以看到每个条形高度的差异.

码:

library(ggplot2)
library(reshape)


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")

print(ggplot(melted,aes(x=x,y=value,fill=variable)) + geom_bar(stat="identity", alpha=.3))
Run Code Online (Sandbox Code Playgroud)

堆叠输出:

在此输入图像描述

jor*_*ran 19

尝试添加position = "identity"到您的geom_bar通话中.你会注意到?geom_bar,默认位置是stack你在这里看到的行为.

当我这样做时,我得到:

print(ggplot(melted,aes(x=x,y=value,fill=variable)) + 
        geom_bar(stat="identity",position = "identity", alpha=.3))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

而且,如下所述,可能position = "dodge"是一个更好的选择:

在此输入图像描述

  • 也许位置应该是"闪避"? (2认同)