share_CO2_generation/generations.py

78 lines
2.9 KiB
Python

import pandas as pd
import matplotlib.pyplot as plt
# The code below fetches the data from the "Our World in Data" Github page.
# This is the data behind this graph/table: https://ourworldindata.org/grapher/cumulative-co-emissions
# If the url does not work you can also use the data provided, by uncommenting the line below.
# df = pd.read_csv('./data/owid-co2-data.csv', header=0)
df = pd.read_csv('https://nyc3.digitaloceanspaces.com/owid-public/data/co2/owid-co2-data.csv', header=0)
# # Select only data for World
df = df[df['country'] == 'World']
# # Select year and Cumulative CO2
df = df[['year','cumulative_co2']]
# Subtract from every cumulative value what has been emitted until 1750
df['cumulative_co2']=df['cumulative_co2']-df['cumulative_co2'].iloc[0]
# For every row:
# 1. Calculate difference between "cumulative CO2 in year i" and "cumulative CO2 in last year" (= total emitted since 1750)
# 2. Divide this difference with "cumulative CO2 in last year"
sums = []
for i in range(len(df)):
share_gen = (df['cumulative_co2'].iloc[-1]-df['cumulative_co2'].iloc[i])/df['cumulative_co2'].iloc[-1]*100
sums.append(share_gen)
# Add the new column of sums to the original DataFrame
df['share_gen'] = sums
# Select every fifth row
df = df.iloc[::5]
# Only for people who were born in the last 100 years
scope = 21
df = df.tail(scope)
# Create a horizontal barplot of year against cumulative_co2
ax = df.plot.barh(x='year', y='share_gen', color = 'silver', width=0.8, linestyle = "")
# Add rasters to the plot
ax.grid(axis='x', linestyle='-', alpha=0.5, color = 'white', zorder=1)
ax.grid(axis='y', linestyle='-', alpha=0.5, color = 'white', zorder=1)
# Add names to axes
ax.set_ylabel('year of birth')
ax.set_xlabel('percentage')
# Add title
ax.set_title('Percentage of global CO2 emissions since 1750\n occurring in your lifetime (valid in %s)' % df['year'].iloc[-1])
# Turn off the legend
ax.legend().set_visible(False)
# Turn on raster
ax.set_xticks(range(0, 101, 10))
# Add explanatory text for year born
year_born = 1987
# Rounding off to five year
diff_year = 5 * round((df['year'].iloc[-1]-year_born)/5)
generation=-(int((diff_year/5)+1))
props = dict(boxstyle='round', facecolor='lightcoral', alpha=0.5)
ax.text(0.63, 0.975, "If you were born in %s,\n%s%% of the total amount \nof CO2 that has been \nemitted since 1750, has \nbeen emitted in your \nlifetime." % (df['year'].iloc[generation], int(df['share_gen'].iloc[generation])), transform=ax.transAxes, fontsize=10,
verticalalignment='top', bbox=props)
ax.patches[generation].set_facecolor('lightcoral')
plt.vlines(x = df['share_gen'].iloc[generation], ymin = -1, ymax = scope+generation, color='lightcoral')
plt.annotate('https://codeberg.org/mishathings/share_CO2_generation', (0,0), (-55,-30), fontsize=6,
xycoords='axes fraction', textcoords='offset points', va='top')
# Save the plot
plt.savefig("output.jpg", dpi=500)