import matplotlib.pyplot as plt
from matplotlib import colormaps
from matplotlib.colors import rgb2hex
import pandas as pd
from packed_bubbles import BubbleChart
from mpl_ornaments.titles import set_title_and_subtitle

#1
fig, ax = plt.subplots(nrows=1, ncols=1, subplot_kw={'aspect':'equal'})

df = pd.read_csv('data/gdp-g7-2010-2020.csv', comment='#')
df = df[df['Year'] == (year := 2020)]
df.sort_values(by='Total', inplace=True, ascending=False)

#2
df['Labels'] = (df['Country'] + '\n(' + 
                df['Total'].map('{:.1f}'.format) + ')')

#3
cpalette = colormaps['Set3'].resampled(lutsize=df['Country'].nunique())

#4
colour_codes = [rgb2hex(c) for c in cpalette.colors]

#5
bubble_chart = BubbleChart(area=df['Total'], bubble_spacing=0.0)

#6
bubble_chart.collapse()

#7
bubble_chart.plot(ax=ax, labels=df['Labels'].to_list(), 
                  colors=colour_codes)
#8
ax.set_axis_off()

#9
ax.autoscale_view()

title = f'GDP of the G7 countries in {year}'
subtitle = 'In bn USD. Source: The World Bank.'
set_title_and_subtitle(fig=fig, title=title, subtitle=subtitle, 
                       alignment='left', h_offset=100)

fig.savefig('charts/packed-bubble-chart.png', dpi=300, 
            bbox_inches='tight')