2014-03-06 34 views
2

朋友, 如何在x轴的两侧创建堆叠barplot(最好在ggplot2中)?穿越x轴的堆叠barplot

例子: http://s23.postimg.org/3lbgicb3f/Example.png

我四处搜寻,但一直没能找到任何很好的例子。 数据由两个位置(1和2)组成,其中包含5个不同类别(A,B,C,R和S)的值(权重)。 A,B和C应位于x轴的上方,而R和S应在下方进行绘制。请注意x轴两侧的正值。没关系错误栏。

示例数据:

Type=c("A","B","C","R","S","A","B","C","R","S") 
Location=c(1,1,1,1,1,2,2,2,2,2) 
Value=c(2,6,5,3,2.5,6,3,2,4,1.5) 
df=data.frame(Type, Location, Value) 
df$Location <- as.factor(df$Location) 

任何指针将不胜感激, Nordenskiold

回答

2

下面是另一种非常类似于@BrodieG的方法,它不需要创建任何新的数据框。

library(plyr) 
library(ggplot2) 
ggplot(df, aes(x=Location, fill=Type))+ 
    geom_bar(subset=.(Type %in% c("A","B","C")), aes(y=Value))+ 
    geom_bar(subset=.(Type %in% c("R","S")), aes(y=-Value))+ 
    geom_hline(yintercept=0, linetype=2)+ 
    scale_y_continuous(labels=abs) 

+0

+ 1用于“子集”位。我有一个微弱的回忆,看到这个记录在某个地方,但无法弄清楚在哪里。此外,感觉有点愚蠢+1后,你会在另一个岗位上这样做,除了绘图,所以这是一个很好的地方,谢谢你教我新的东西。 – BrodieG

+0

太棒了,这正是我所寻找的。非常感谢! – Nordenskiold

+0

@Nordenskiold,如果您的问题得到解答,请考虑标记其中一个答案作为答案。谢谢。 – BrodieG

1

你可以试试:

df <- transform(df, Value=ifelse(as.character(Type) %in% c("R", "S"), -Value, Value)) 
df.split <- split(df, df$Value < 0) 

ggplot() + 
    geom_bar(data=df.split[[1]], aes(x=Location, y=Value, fill=Type), stat="identity") + 
    geom_bar(data=df.split[[2]], aes(x=Location, y=Value, fill=Type), stat="identity") + 
    geom_hline(yintercept=0) + 
    scale_y_continuous(labels=abs) 

enter image description here

在这里我们需要分割数据框架成正面和负面tive值,然后我们使用label参数scale_y_continous使y轴上的所有值都为正值。

+1

+1'标签= abs' – jlhoward

+0

非常感谢你的帮助。非常感激! – Nordenskiold