import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from mpl_ornaments.titles import set_title_and_subtitle

fig, ax = plt.subplots(nrows=1, ncols=1)

df = pd.read_csv('data/gdp-g7-2010-2020.csv', comment='#')

#1
years = np.sort(df['Year'].unique()); num_years = len(years)

#2
sorted_indices = df[df['Year'] == years[-1]]['Total'].argsort()[::-1]
countries_by_gdp = df[df['Year'] == years[-1]].iloc[sorted_indices]['Country'].to_list()

#3
bar_width = 0.4

#4
offsets = np.linspace(start=0, stop=bar_width*(num_years-1), 
                      num=num_years)
offsets = offsets - np.mean(offsets)

#5
x_ticks_pos = np.arange(df['Country'].nunique())

#6
for (year, offset) in zip(years, offsets):
    
#7
    x_pos = x_ticks_pos + offset
    
#8
    df_year = df[df['Year'] == year]
    df_data = df_year.iloc[pd.Index(df_year['Country']).get_indexer(
        countries_by_gdp)]
    
#9
    ax.bar(x=x_pos, height=df_data['Total'], width=bar_width, 
           label=f'{year:d}')

#10
ax.set_xticks(ticks=x_ticks_pos)
ax.set_xticklabels(labels=countries_by_gdp)

#11
ax.legend(title='Year')

#12
ax.grid(visible=True, which='major', axis='y')
#13
ax.set_axisbelow(True)

ax.spines[['top', 'right', 'left']].set_visible(False)

title = f'GDP of the G7 countries in {years[-1]} and {years[0]}'
subtitle = f'In bn USD. Source: The World Bank.'
set_title_and_subtitle(fig=fig, title=title, subtitle=subtitle, 
                       alignment='left', h_offset=25)

fig.savefig('charts/paired-bar-chart.png', dpi=300, bbox_inches='tight')