如何为 ggplot2 和具有负值的堆叠条形图准备数据?

How to prepare data for ggplot2 and stack bar chart with negative values?

给定以下数据集:

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

理想情况下,在 'row' 列而不是数字中,我将使用 Market io 1、Geography io 2、Industry io 3,以便我用不同的(市场、地理)填充条形图, Industry) 类别而不是 1-2-3.Also dat2 中的第 1 行到第 3 行应该被删除,因为它们不对应于季度数据。谢谢!

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)

我在下面试了一下,但我对你的粗体问题感到很困惑。您数据的奇怪格式似乎是由使用 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)