from IPython.display import HTML
HTML('''<button type="button" class="btn btn-outline-danger" onclick="codeToggle();">Toggle Code</button>''')
Our data set contains information about the CO2 and other greenhouse gas emissions from many countries spread across the timeline from 1750 to 2020. Mainly the data consists of overall CO2 production annually, sources of CO2 production and their contribution amount to the overall CO2 emissions. We are given data for global and country wise CO2 consumption from different sources of CO2 for example CO2 emission from coal, oil, and gas. Besides the data regarding CO2 , the dataset consists of other related factors like GDP of countries and the energy consumption of countries over the years. We have also used a dataset for sea level to compare the effects of global warming.
import pandas as pd
import numpy as np
from matplotlib import animation
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
from matplotlib import animation
import plotly.express as px
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from IPython.display import display
import ipywidgets as widgets
import plotly.graph_objects as go
import warnings
warnings.filterwarnings('ignore')
parent_db = pd.read_csv("./data/owid-co2-data.csv")
temperature_db = pd.read_csv("./data/annual_csv.csv")
sea_db = pd.read_csv("./data/csiro_recons_gmsl_yr_2015_csv.csv")
def clean_df(db):
non_countries = ['World','Asia','Asia (excl. China & India)','North America','Europe','North America (excl. USA)','EU-27','EU-28','Europe (excl. EU-27)','Europe (excl. EU-28)','International transport','Kuwaiti Oil Fires','Africa']
for place in non_countries:
db = db[db.country != place]
return db
db = clean_df(parent_db)
world_data = parent_db[parent_db.country == "World"]
all_countries = db['country'].unique()
all_columns = db.columns
countries_list = ["United States","China","Russia","India"]
co2_types = ["co2","coal_co2",'cement_co2','gas_co2','oil_co2','trade_co2','methane','nitrous_oxide','other_industry_co2']
co2_types1 = ["co2","coal_co2",'gas_co2','oil_co2']
energies = ["primary_energy_consumption" ,"energy_per_capita" ,"energy_per_gdp"]
top_countries = ["China", "United States", "India", "Russia"]
num_countries = len(all_countries)
world_data_co2s = world_data[["year","country"]+co2_types]
world_co2_2000 = world_data[world_data.year>2000][["year","country"]+co2_types1]
fig = px.line(world_co2_2000, x="year", y=co2_types1,labels={
"value": "CO2 (Million tonnes)"},template="plotly_dark")
fig.show()
geo_data = db[db.year>1980][["iso_code","country","year","co2"]].dropna()
fig = px.scatter_geo(geo_data, locations="iso_code", color="country",
hover_name="country", size="co2",
projection="natural earth", animation_frame="year", template="plotly_dark",title = "CO2 emmisions over time for all countries")
fig.show()
On considering information about CO2 emissions, we had around 34.8 billion tonnes in 2020. When the fourth industrial revolution started, we had 25.2 billion tonnes of CO2 production 20 years ago. In the fourth industrial revolution, we have got internet and renewable energy resources like solar, wind and tidal energies. Even after a shift towards renewable sources, we see a massive increase in production because the digital world has a real-time connection and more productions in various sectors like pharmacy, agriculture, etc. Many of them are responsible for greenhouse gas emissions.
d = {}
for year in range(2000,2018):
d[year] = world_past_250[world_past_250.year == year]["co2"].values[0]
li = list(d.values())
inc = (np.diff(li)/li[:-1])*100
i=0
_max = 0
_year = 0
strs = []
for year in range(2000,2017):
strs.append(str(round(inc[i],3))+"%")
_max = max(_max,inc[i])
if(_max == inc[i]):
_year = year
i+=1
print("Maximum increase in CO2 emission between 2000-2018 happend in {} with a {}% increase in global CO2 emission.".format(_year,round(_max,3)))
Maximum increase in CO2 emission between 2000-2018 happend in 2009 with a 5.493% increase in global CO2 emission.
During the past ten years, has the world woken up to the disturbing fact that it is suffocating in carbon emissions. Many countries have come forward to address this issue through agreements, policies, and resolutions. We noticed that the production of CO2 emissions did not decrease but rather increased over the past five years. Even though these resolutions are considered revolutionary in addressing the issue, they have had minimal effect in changing the direction in which the world is moving.
fig = go.Figure(data=[
go.Bar(x=world_past_250['year'].values, y=world_past_250['co2'].values,text = strs,textposition='outside')
])
fig.update_layout(
title="Change in CO2 emmsion over time",
xaxis_title="Global CO2 emmision in million tonnes",
yaxis_title="Year",template="plotly_dark"
)
fig.show()
We can see the relative change in CO2 emmision for the past 20 years. It has been increasing around 2-3% every year in the first 10 years. It has relatively stagnated in the last 10 years
dff = db[(db.country == "Canada") | (db.country == "China") |(db.country == "United States") |(db.country == "Russia")|(db.country == "Japan")|(db.country == "India")][db.year > 2000] [["country","co2","year"]]
fig = px.bar(dff, x="country", y="co2", color="country",
animation_frame="year", animation_group="country",title="Top CO2 emmision countries over time",labels={
"co2": "CO2 emmision (million tonnes)",
"country": "Country"})
fig.show()
From 2000 onwards, four countries contributed to 50% of CO2 emissions. They are China, United States(USA), India, and Russia. China and USA constitute 41 % of CO2 emissions. Humans utilised these sources for their needs, and they neglected the negative impact caused by them on the environment.
def co2_dist(year):
req_cols = ["country","year"]+co2_types
req_cols.remove("trade_co2")
co2_world_dist = world_data[world_data.year>1990][req_cols]
co2_world_dist[["coal_co2","gas_co2","cement_co2","oil_co2","methane","nitrous_oxide","other_industry_co2"]] = (co2_world_dist[["coal_co2","gas_co2","cement_co2","oil_co2","methane","nitrous_oxide","other_industry_co2"]].div(co2_world_dist.co2, axis=0))*100
co2_world_dist = co2_world_dist[co2_world_dist.year == year].transpose().reset_index()
co2_world_dist.columns = co2_world_dist.iloc[1]
co2_world_dist.rename(columns = {'year':'type_co2',year:'percentage'}, inplace = True)
co2_world_dist.drop([0,1,2], axis=0, inplace=True)
return co2_world_dist
fig = px.pie(co2_dist(2020), values='percentage',names = 'type_co2',title = "Distribution of overall CO2 emmision in 2020")
fig.show()
fig = px.pie(co2_dist(2000), values='percentage',names = 'type_co2',title = "Distribution of overall CO2 emmision in 2000")
fig.show()
From the pie charts, CO2 emissions from coal has been the highest contributing source in the overall CO2 emissions accounting for 40.7% of CO2 emissions in 2020. The amount of total CO2 emission in 2000 was 25.4k million tonnes The amount of total CO2 emission in 2020 was 34.8k million tonnes. Furthermore, it is noteworthy to point out that percentage of coal CO2 emission contributing to the overall global emissions has increased from 26.1% in 2000 to 40.7% in 2020,
country_co2_gdp_corr = db.groupby("country")["co2"].corr(db["gdp"]).to_frame().reset_index()
country_co2_gdp_corr["gdp"] = db[db.year == 2018][["year","country","gdp"]]["gdp"].values
country_co2_gdp_corr = country_co2_gdp_corr.dropna()
country_co2_gdp_corr = country_co2_gdp_corr.sort_values(by = ["gdp"],ascending = False)
temp_df = country_co2_gdp_corr.head(20)
fig = px.scatter_3d(temp_df, x='country', y='co2', z='gdp',
color='country', labels={
"co2": "correlation factor",
"gdp": "GDP"},
template="plotly_dark")
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()
print("Corelation between world GDP and global co2 emission:",world_data['gdp'].corr(world_data['co2']))
Corelation between world GDP and global co2 emission: 0.9716498642763861
The correlation factor world GDP and global CO2 emissions is 0.971, which is very high. It simply indicates that change in GDP and increase in CO2 is almost in a linear relationship. However, some countries like Russia, the United Kingdom, Germany, and France increased their GDP with low correlation constants such as 0.24, 0.63, 0.74, and 0.8, respectively. It shows us that fueling the GDP growth via carbon emission is unnecessary for development. Those Countries that rely on CO2 emissions for their GDP growth must adapt and follow the methods currently used by the countries for increasing their GDP without damaging the environment.
world_energy = world_data[(world_data.year > 1980) & (world_data.year <2020)][["year","country"]+energies]
avg_energy = world_energy[world_energy.year>1980]["primary_energy_consumption"].values/num_countries
world_energy = world_energy.assign(avg_energy=avg_energy)
fig = px.bar(world_energy, x='year', y='avg_energy',labels={
"avg_energy": "Average primary energy consumption",
"year": "Year"},title = "Primary energy consumption of the world",template="plotly_dark")
fig.show()
Another factor related to the CO2 emissions is the world population, as it directly increases the energy demand. The world's population increased from 745 million in 1750 to 7.8 billion in 2020. The average primary energy consumption over the past 50 years is 24241, 17794, 4308, and 8870 in the United States of America, China, India, and Russia, respectively.
During the past ten years, has the world woken up to the disturbing fact that it is suffocating in carbon emissions. Many countries have come forward to address this issue through agreements, policies, and resolutions. We noticed that the production of CO2 emissions did not decrease but rather increased over the past five years. Even though these resolutions are considered revolutionary in addressing the issue, they have had minimal effect in changing the direction in which the world is moving. Let us look into the CO2 production and its causes in some countries.
def show_country_stat(country,year,co2s,marker_year):
db_uk = db[(db.country == country) & (db.year>=year)][co2s]
fig = px.line(db_uk, x="year", y=co2s,labels={
"value": "CO2 (Million tonnes)"},template="plotly_dark",title = "CO2 emmisions in {} from {} onwards".format(country,year))
if(country == "United Kingdom"):
fig.add_scatter(x=[marker_year],y = db_uk[db_uk.year == marker_year]['co2'].tolist(),marker = dict(size = 15, color = "#19D3F3"))
elif(country == "United States"):
y_vals = db_uk[db_uk.year == 2009].values[0][1:]
x_vals = [marker_year]*len(y_vals)
fig.add_scatter(x=x_vals,y =y_vals ,mode = 'markers',marker = dict(size = 15, color = "#FFFFFF"))
return fig
fig = show_country_stat("United Kingdom",2005,['year','co2'],marker_year = 2009)
fig.show()
In 2009, there was a downfall in CO2 emissions by 9 per cent in the United Kingdom from 545 to 494 million metric tonnes. This is because of establishing a new act - Climate Change Act, introduced in 2008. This act allows the UK to become a low carbon economy and reduce greenhouse gas emissions at the end of 2050 by 100% lower than the 1990 baseline. It is the first country to take the initiative to set emission targets. The CO2 emissions in the United Kingdom are gradually decreasing from the year 2009. However, CO2 emissions are increased in year 2010 compared to year 2009. The United Kingdom had reduced CO2 emissions by 32 per cent by the end of 2019. Britain is one of the successful countries that reduced CO2 emissions.
fig = show_country_stat("United States",2005,['year','co2','coal_co2','oil_co2'],marker_year = 2009)
fig.show()
Again in the year 2009, CO2 emissions fell by 7 per cent from 5.9 to 5.5 billion metric tonnes in the United States because of the impact of economic recession and the shift from coal to clean-burning natural gas to produce electricity. They shifted to natural gas since the price of natural gas has been declined. We can see that decline in CO2 emissions comes mostly from less consumption of coal which is reduced by around 12 per cent, and gas consumption decreased by five per cent. Through its policies and government laws, the US reduced its emissions by 11 per cent in 2019.
fig = show_country_stat("India",2005,['year','co2','coal_co2','oil_co2'],marker_year=None)
fig.show()
India is a developing country. Industrialisation is one of the major sectors of India’s economy. India is the third-largest country in CO2 emissions after China and US. India needs to take proper measures as it contributes enormous amounts to CO2 production. India introduced policies to control CO2 emisssions. However, India is unable to control it. CO2 emissions from coal and oil are continuously increasing from the year 2000 to 2019 due to it’s economy.
Some of the policies India came up with are - The government of India had launched the National Action Plan on Climate Change (NAPCC) in the year 2008, having eight national missions; The Paris agreement is a legally binding international treaty on climate change. India is one of the countries that had signed the Paris agreement on October 2, 2016. According to the Paris agreement, the signed countries should curb CO2 emissions and maintain the global average temperature less than 20C. There was a decrease of 0.125% in Global CO2 emissions from 2015 to 2016.
df = temperature_db
df1 = pd.DataFrame(columns = ["Source","Year","Mean"])
r,c = df.shape
i = 0
j = 0
while i<r:
row = temperature_db.iloc[i]
df1.loc[j] = row
i = i+2
j = j+1
fig = px.scatter(df1, x="Year", y="Mean", title="Variation in global Tempertaure over time",labels={
"Mean": "Mean temperature"},template="plotly_dark")
fig.show()
The Global temperature in 1990 was 0.430C. In 2016, It is increased to 0.940C. Global warming results in a bad impact on melting glaciers which in turn increases sea level.
sea_db["Time"]= sea_db["Time"].str.slice(0, 4, 1)
sea_db = sea_db[sea_db.Time>'1985']
fig = px.line(sea_db, x="Time", y="GMSL",labels={
"GMSL": "Mean sea level"},template="plotly_dark",title = "Change in sea level over the years")
fig.show()
In 1990 the global mean sea level crossed the zero mark and within a span of 10 years, it reached 65 mm. The effect of an increase in sea level can worsen the habitat of many organisms. It also puts many Oceania countries at risk.
Some countries like UK and USA are trying to reduce the CO2 emissions by introducing policies. Other countries must follow those countries steps and reduce the CO2 emissions in order to save the earth from global warming.