0
votes

I'm trying to create a stacked identity barplot but ggplot2 keeps lumping my data together.

Instead of providing the stacked plot with each respective categories for each sector, it's aggregating the direct, indirect.down and indirect.up categories together.

test.df = data.frame(scenario=(c("s1", "s1", "s1", "s2", "s2", "s2", "s3", "s3", "s3",
                             "s1", "s1", "s1", "s2", "s2", "s2", "s3", "s3", "s3",
                             "s1", "s1", "s1", "s2", "s2", "s2", "s3", "s3", "s3")),
              sector=(c("Agriculture", "Manufacturing", "Services", "Agriculture", "Manufacturing", "Services", "Agriculture", "Manufacturing", "Services",
                        "Agriculture", "Manufacturing", "Services", "Agriculture", "Manufacturing", "Services", "Agriculture", "Manufacturing", "Services",
                        "Agriculture", "Manufacturing", "Services", "Agriculture", "Manufacturing", "Services", "Agriculture", "Manufacturing", "Services" )),
              loss=(runif(27,0,1000)), shock=(c("direct", "indirect.up", "indirect.down","direct", "indirect.up", "indirect.down","direct", "indirect.up", "indirect.down",
                        "direct", "indirect.up", "indirect.down","direct", "indirect.up", "indirect.down","direct", "indirect.up", "indirect.down",
                        "direct", "indirect.up", "indirect.down","direct", "indirect.up", "indirect.down","direct", "indirect.up", "indirect.down")))

library(ggplot2)

ggplot(test.df, aes(x=sector, y=loss)) + geom_bar(stat = "identity", aes(fill=shock))  + facet_wrap(~ scenario) + coord_flip()

I want it to look like this in terms of how the shocks to each sector are stacked:

enter image description here

1

1 Answers

1
votes

That's because in your sample data, each sector has only one kind of shock associated to it.

table(test.df$sector, test.df$shock)

#              direct indirect.down indirect.up
# Agriculture        9             0           0
# Manufacturing      0             0           9
# Services           0             9           0

Adding some data to create some more associations between sector and shock:

df2 <- test.df

df2$shock[df2$shock == "indirect.down"] <- "indirect.up"
df2$shock[df2$shock == "direct"] <- "indirect.down"

test.df <- rbind(test.df, df2)

table(test.df$sector, test.df$shock)

#               direct indirect.down indirect.up
# Agriculture        9             9           0
# Manufacturing      0             0          18
# Services           0             9           9

Test your code now:

library(ggplot2)

ggplot(test.df, aes(x=sector, y=loss)) +
 geom_bar(stat = "identity", aes(fill=shock))  +
 facet_wrap(~ scenario) + coord_flip()

enter image description here