Jamalan
Jamalan

Reputation: 580

How do I plot a stacked bar chart, given percentages?

How do I plot a stacked bar chart using ggplot2?

Given the below data, I want year on the x-axis, and the y-axis to be treated as stacked, with late_percent as the proportion.

I want the y-axis filled with 2 colors based on the percentage given: 0.16 means 16% one color and 84% another color; apply this the same all the way across for every year.

This is my dataframe:

   year   percent
1: 2015   0.16
2: 2016   0.23
3: 2017   0.14
4: 2018   0.64
5: 2019   0.15
6: 2020   0.24

I have tried:

ggplot(data = mydata)+
geom_bar(aes(x = year, y = percent),position = 'fill', stat = 'identity')

Upvotes: 1

Views: 637

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145775

ggplot will only plot data that's there. You want to include data that's implied, but not actually there, (1 - percent). We'll create it explicitly, and then the plotting will go easily.

data %>%
  mutate(percent = 1 - percent, type = "not there") %>%
  bind_rows(data) %>%
  mutate(type = coalesce(type, "there")) %>%
  ggplot(aes(x = year, y = percent, fill = type)) +
  geom_col() +
  scale_y_continuous(labels = scales::percent)

enter image description here

These days, geom_col is preferred to geom_bar(stat = 'identity'), and it stacks by default.

Of course, change the labels and colors to whatever you want them to be.


Using this sample data

data = read.table(text = '   year   percent
1: 2015   0.16
2: 2016   0.23
3: 2017   0.14
4: 2018   0.64
5: 2019   0.15
6: 2020   0.24', header = T)

Upvotes: 2

Related Questions