Skip to content

Instantly share code, notes, and snippets.

@dubsnipe

dubsnipe/world_co2.R

Last active Jan 14, 2020
Embed
What would you like to do?
This script generates a CO2 worldwide emissions chart based on World Bank data.
fileUrl <- "http://api.worldbank.org/v2/en/topic/19?downloadformat=csv"
dataset <- "wbco2_dataset.zip"
download.file(
fileUrl,
dataset,
mode = "wb"
)
zip_list <- unzip(dataset, list=T)
file_names <- zip_list$Name
unzip(dataset, exdir="./CO2_Data")
# List of downloaded files.
file_names
co2_data <- as_tibble(read.csv("CO2_Data/API_19_DS2_en_csv_v2_613774.csv", skip=4, header=T))
co2_per_year <- co2_data %>%
filter(Country.Name == "World", Indicator.Code == "EN.ATM.CO2E.KT") %>%
select(-Country.Name, -Country.Code, -Indicator.Name, -Indicator.Code) %>%
gather(key="year", value="value")
co2_per_year$year <- co2_per_year$year %>% str_extract("\\d{4}") %>% as.numeric()
co2_per_year <- co2_per_year %>% drop_na()
co2_per_year
year_range <- paste0(co2_per_year$year %>% min(), "-", co2_per_year$year %>% max())
plot_title <- paste0("CO2 Emissions ", year_range, " (Source: World Bank)")
g <- ggplot(co2_per_year, aes(x=year, y=value)) +
geom_line(color="blue", size=2) +
ggtitle(plot_title) +
xlab("Year") +
ylab("CO2 emissions (kt)") +
theme_bw()
g
# Exporting image
png_filename <- paste0("CO2_Data/CO2_World_", year_range, ".png")
png(file = png_filename, bg = "transparent", width = 1280, height = 800, units = "px", pointsize = 12)
g
dev.off()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.