US CO2 emissions by source

library(pacman)
p_load(tidyverse, scales, ggthemes, RColorBrewer, plotly)

energy_cons  <- read_csv("https://www.eia.gov/totalenergy/data/browser/csv.php?tbl=T12.01")

energy_cons  %>% glimpse
## Observations: 8,302
## Variables: 6
## $ MSN          <chr> "CKTCEUS", "CKTCEUS", "CKTCEUS", "CKTCEUS", "CKTC...
## $ YYYYMM       <dbl> 197301, 197302, 197303, 197304, 197305, 197306, 1...
## $ Value        <dbl> 108.289, 97.698, 97.366, 93.084, 94.346, 97.757, ...
## $ Column_Order <dbl> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
## $ Description  <chr> "Coal, Including Coal Coke Net Imports, CO2 Emiss...
## $ Unit         <chr> "Million Metric Tons of Carbon Dioxide", "Million...
energy_cons_totals  <- energy_cons  %>%
    mutate(YYYYMMDD = paste0(YYYYMM, "01"), #get into format so can use lubridate
           date = lubridate::ymd(YYYYMMDD),
           year = lubridate::year(date),
           description = factor(Description),
           description = case_when(
               grepl("Coal", description) ~ "Coal",
               grepl("Natural Gas", description) ~ "Natural Gas",
               grepl("Petroleum", description) ~ "Petroleum",
               # grepl("Jet Fuel", description) ~ "Jet Fuel",
               grepl("Motor Gasoline", description) ~ "Motor Gasoline",
               grepl("Total Energy", description) ~ "Total Energy",
               TRUE ~ "Other")
    ) %>%
  group_by(year, description)  %>%
  filter(!is.na(year))  #Months that were 13 were annual totals became na when converted to date (these are filtered out)


energy_cons_totals  %>% filter(description != "Total Energy" & year != 2018  & year >= 1990)  %>%
    summarize(total = sum(Value, na.rm = TRUE))  %>%
    ggplot(aes(x = year, y = total, fill = fct_reorder(description, total))) +
    labs(title = "CO2 emissions in the US by source",
         # subtitle = "amounts in millions of tonnes",
         x = "",
         y = "Amount",
         fill = "") +
    geom_col() + theme_fivethirtyeight()  + scale_fill_brewer(palette = "Greys") -> p


ggplotly(p)

Related