横跨x轴的堆积的barplot

时间:2014-03-06 21:40:19

标签: r ggplot2 bar-chart

友 如何在x轴的两侧创建堆叠条形图(最好是在ggplot2中)?

实施例: 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 个答案:

答案 0 :(得分:2)

您可以尝试:

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

这里我们需要将数据框拆分为正值和负值,然后我们使用label参数scale_y_continous来使y轴上的所有值都为正。

答案 1 :(得分: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)