如何使用负值为ggplot2和堆栈条形图准备数据?

时间:2017-02-28 15:35:21

标签: r ggplot2 melt geom-bar

给出以下数据集:

Output<- read.table(text = "Type   2012-06-30' 2012-09-30
 1   Market     2  3    
 2   Geography  3  -2
 3   Industry   -1 5 ",header = TRUE,sep = "",row.names = 1)

我尝试准备数据以便使用ggplot2包并创建一个带负值的堆积条形图。这是我使用的基本图表序列:

Output$row <- seq_len(nrow(Output))
dat2 <- melt(Output, id.vars = "row")

但是这给了我:

dat2
       row     variable     value
    1   1         Type    Market
    2   2         Type Geography
    3   3         Type  Industry
    4   1 X2012.06.30.         2
    5   2 X2012.06.30.         3
    6   3 X2012.06.30.        -1
    7   1  X2012.09.30         3
    8   2  X2012.09.30        -2
    9   3  X2012.09.30         5

理想情况下,在&#39;行中列而不是数字我会有Market io 1,Geography io 2,Industry io 3以便我用不同的(市场,地理,行业)类别填充我的条形图而不是1-2-3。还有行1到3应该删除dat2,因为它们不对应于四分之一数据。谢谢!

dat1 <- subset(dat2,value >= 0)
dat3 <- subset(dat2,value < 0)
ggplot() + 
  geom_bar(data = dat1, aes(x=variable, y=value, fill=row),stat = "identity") +
  geom_bar(data = dat3, aes(x=variable, y=value, fill=row),stat = "identity") +
  scale_fill_brewer(type = "seq", palette = 1)

1 个答案:

答案 0 :(得分:0)

我在下面试了一下,但我对你粗体问题很困惑。数据的奇怪格式似乎是由使用id.vars = "row"引起的,但请在需要时澄清。

Output<- read.table(text = "Type   2012-06-30' 2012-09-30
    1   Market     2  3
    2   Geography  3  -2
    3   Industry   -1 5 ",header = TRUE,sep = "",row.names = 1)

melt(Output)

dat2 <- melt(Output)
dat1 <- subset(dat2,value >= 0)
dat3 <- subset(dat2,value < 0)

ggplot() +
   geom_bar(data = dat1, aes(x=variable, y=value, fill=Type),stat = "identity") +
   geom_bar(data = dat3, aes(x=variable, y=value, fill=Type),stat = "identity") +
   scale_fill_brewer(type = "seq", palette = 1)

enter image description here