Total lines on a Stacked Bar Chart in ggplot2

Viewed 28

I have a country level dataset with two types of data as shown here:

Country Type Value Total
Austria Public - 0.2 0.3
Austria Private 0.5 0.3
Belgium Public - 0.1 0.1
Belgium Private 0.2 0.1

I was wondering how it would be possible to demarcate the Total column, which is the sum total of both types as a line upon the stacked barchart of both the values in the Type column.

The code for my stacked barchart is here:

ggplot(aes(x = Value, y = reorder(Country, Total), fill = Type)) + geom_bar(stat = "identity", color = "black") +
    scale_fill_manual(values=c("#1E8BC3", "#E85B4E")) + geom_vline(xintercept = 0, size = 1)
1 Answers

One option would be to sue stat_summary to compute the totals from the data:

library(ggplot2)

ggplot(dat, aes(x = Value, y = reorder(Country, Total), fill = Type)) + 
  geom_bar(stat = "identity", color = "black") +
  stat_summary(aes(group = 1, color = "Total"), fun = sum, geom = "line") +
  scale_color_manual(values = "black") +
  scale_fill_manual(values=c("#1E8BC3", "#E85B4E", "black")) + 
  geom_vline(xintercept = 0, size = 1)

A second option would be to use geom_line and the Total column in your dataset, where for the data I use dplyr::distinct(.x, Country, Total) to get rid of the duplicated totals per country:

ggplot(dat, aes(x = Value, y = reorder(Country, Total), fill = Type)) +
  geom_bar(stat = "identity", color = "black") +
  geom_line(dat = ~ dplyr::distinct(.x, Country, Total), aes(x = Total, y = Country, group = 1, color = "Total"), inherit.aes = FALSE) +
  scale_color_manual(values = "black") +
  scale_fill_manual(values = c("#1E8BC3", "#E85B4E", "black")) +
  geom_vline(xintercept = 0, size = 1)

DATA

dat <- data.frame(
           Country = c("Austria", "Austria", "Belgium", "Belgium"),
              Type = c("Public", "Private", "Public", "Private"),
             Value = c(-0.2, 0.5, -0.1, 0.2),
             Total = c(0.3, 0.3, 0.1, 0.1)
)
Related