Lital Dayan
Lital Dayan

Reputation: 27

R stacked percentage bar plot with percentage of binary factor and labels

I want to produce a graphic that looks something like this (with percentage and legend) by R:

enter image description here

My original data is:

         AIRBUS BOEING EMBRAER
  2002     18     21      30
  2003     20     23      31
  2004     23     26      29
  2005     22     25      26
  2006     22     25      25
  2007     22     27      17
  2008     21     21      16
  2009     17     19      22
  2010     14     22      24
  2011     17     27      22
  2012     16     22      19
  2013     11     24      19

enter image description here

There are similar questions on SO already, but I seem to lack the sufficient amount of intelligence (or understanding of R) to extrapolate from them to a solution to my particular problem.

Upvotes: 1

Views: 745

Answers (1)

Jack Brookes
Jack Brookes

Reputation: 3830

First, gather or melt your data into long format. Then it's easy.

library(tidyverse)

df <- read.table(
  text = "
  YEAR AIRBUS BOEING EMBRAER
  2002     18     21      30
  2003     20     23      31
  2004     23     26      29
  2005     22     25      26
  2006     22     25      25
  2007     22     27      17
  2008     21     21      16
  2009     17     19      22
  2010     14     22      24
  2011     17     27      22
  2012     16     22      19
  2013     11     24      19",
  header = TRUE
)


df_long <- df %>% 
  gather(company, percentage, AIRBUS:EMBRAER)

ggplot(df_long, aes(x = YEAR, y = percentage, fill = company)) + 
  geom_col() + 
  ggtitle("Departure delays by company and Year") + 
  scale_x_continuous(breaks = 2002:2013)

enter image description here

Upvotes: 1

Related Questions