# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: jupyter_street
#     language: python
#     name: jupyter_street
# ---

# # Background

# Out of curiosity I wanted to visualize the relationship between global economic growth, carbon emissions and energy use.

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# %matplotlib inline
# %config InlineBackend.figure_format = 'svg'
plt.style.use('ggplot')

sns.set_style("whitegrid")
colors = sns.color_palette("Set2")

# ## Carbon emissions

# Carbon emissions are taken from the reference below. The unit shown will be in *Thousand metric tons*.

# **Reference:**
#
# National CO2 Emissions from Fossil-Fuel Burning, Cement Manufacture, and Gas Flaring: 1751-2014      
#                                                      
# *doi 10.3334/CDIAC/00001_V2017*
#                                                      
# March 5, 2017                                       
#                                                      
# Source:
# <NAME>, <NAME>                                 
# Carbon Dioxide Information Analysis Center 
# Oak Ridge National Laboratory              
# Oak Ridge, Tennessee 37831-6290 USA        
#                                                      
# <NAME>                              
# Research Institute for Environment, Energy and Economics                            
# Appalachian State University               
# Boone, North Carolina, 28608-2131 USA      

f = "nation.1751_2014.ems"
c = {}
with open(f, 'r') as fhin:
    for line in fhin:
        line = line.rstrip()
        try: 
            y = int(line[0:4])
            emission = int(line.rsplit()[1])
            try:
                c[y]+=emission
            except KeyError:
                c[y] = emission
        except ValueError:
            continue
em = pd.DataFrame(c, index=["C"]).T.sort_index()

# ### Carbon emissions per year

# The plot below shows annual carbon emissions.

ax = em.plot(legend=None)
ax.set_ylabel("Thousand metric tons");

# ## Gross Domestic Product (GDP)

# Global GDP is taken from the reference below. It will be shown as *trillion $USD*.

# **Reference:**
#
# https://data.worldbank.org/indicator/NY.GDP.MKTP.CD

gdp = pd.read_csv("GDP_per_country.tsv", sep="\t", header=0)
gdp = gdp.loc[(gdp["Series Name"]=="GDP (current US$)")&(gdp["Country Name"]=="World"), list(gdp.columns)[4:]]
gdp = gdp.T
gdp.rename(index=lambda x: int(x[0:4]), inplace=True)
gdp.columns = ["GDP"]
# Divide by 10^12 to get trillions
gdp = gdp.assign(GDP_trill = pd.Series(gdp.GDP/1000000000000, index=gdp.index))

# ### GDP per year

# The figure below shows World GDP from 1960 to 2018.

ax = gdp.loc[:,"GDP_trill"].plot()
ax.set_ylabel("GDP (trillion $USD)");

# We see that with a few exceptions there's been a steady increase in GDP globally.

# ### Comparing emissions and GDP

# Below we will merge the emission and GDP data and plot together.

df = pd.merge(gdp, em, left_index=True, right_index=True, how="inner")

ax1 = df.C.plot(color=colors[0])
ax1.set_ylabel("Thousand metric tons");
ax2 = df.GDP.plot(color=colors[1], secondary_y=True)
ax1.legend(bbox_to_anchor=(0.4,1))
ax2.legend(bbox_to_anchor=(0.445,0.9))
ax2.set_ylabel("GDP ($USD)");

# This shows that carbon emission is tracking GDP very well.

# ### Calculate carbon intensity of GDP

# Below we look at how much carbon is emitted per $USD of GDP created. This is the 'carbon intensity' of the economy.

#Divide emissions by GDP to get C emissions per $USD.
df = df.assign(C_USD = pd.Series(df.C.div(df.GDP), index=df.index))

# The figure below shows carbon emissions per $USD.

ax = df.C_USD.plot()
ax.set_ylabel("Thousand metric tons / $USD");

# This shows the relative decoupling of the economy: i.e. more GDP is produced per emitted unit of carbon. **However**, as we noted above there is no absolute decoupling. This means that all the efficiency gain is used to produce even more GDP and increase the amount of carbon emitted.

# ### Regression of GDP and carbon emitted

# Perform a simple regression of GDP and C.

sns.lmplot(data=df.loc[:,["GDP","C"]], x="GDP", y="C", robust=True)

# The correlation of carbon emitted and GDP is very high.

# # Energy

# Here we look at the amount of energy being used globally.

# **Reference:**
#
# Energy consumption from [BP energy review](https://www.bp.com/en/global/corporate/energy-economics/statistical-review-of-world-energy/downloads.html).

en = pd.read_csv("world_energy.tsv", sep="\t", header=0, index_col=0).T
en.columns = ["Energy"]
en.rename(index = lambda x: int(x), inplace=True)
ax = en.plot(legend=None)
ax.set_ylabel("Million tonnes oil equivalent");

# This shows a steady increase in global energy consumption.

# ### Comparing energy consumption and GDP

table = pd.merge(df, en, left_index=True, right_index=True)
table.head()

ax1 = table.Energy.plot(color=colors[2])
ax1.legend(bbox_to_anchor=(0.445,0.9))
ax2 = df.GDP.plot(color=colors[1], secondary_y=True)
ax2.legend(bbox_to_anchor=(0.4,1))
ax2.set_ylabel("GDP ($USD)");

# Again we see that energy consumption is tracking GDP very well. Not surprising really since we use energy to perform activity, including economic activity.

# ### Regression of GDP and energy consumption

# Perform regression of energy and GDP.

sns.lmplot(data=table, x="GDP", y="Energy", robust=True)

# As for carbon emitted, there is a strong correlation between GDP and energy consumption.

# ## Integrating all the data

# Below I attempt to visualize GDP, carbon emissions and energy consumption together.

ax = sns.scatterplot(data=table, x="GDP", y="C", hue="Energy", palette="RdBu_r", size="Energy")
ax.legend(bbox_to_anchor=(1,1));

# In this plot each point is a year. Carbon emissions are shown on the y-axis and GDP on the x-axis. The size and color of the point corresponds to the energy consumption for that year: big and red = high energy consumption.

ax = sns.scatterplot(data=table.reset_index().rename(columns = {'C': 'Carbon'}), x="index", y="GDP_trill", size="Carbon", hue="Energy", palette="coolwarm")
[t for t in ax.legend().get_texts()]
ax.legend(bbox_to_anchor=(1,1))
ax.set_xlabel("Year");
ax.set_ylabel("GDP (Trillion $USD)");
plt.savefig("BNP_energi_C.png", dpi=300, bbox_inches="tight")

# In this plot the x-axis corresponds to years and the GDP is shown on the y-axis. The size of each point indicates the amount of carbon emitted in that year (larger = more carbon). The color of the point shows the energy consumption (more red = more energy).

StarcoderdataJupyterScriptsDedupFiltered