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/age-distribution-usa-2022.csv', comment='#')
df['Percentage'] = 100*df['Population']/df['Population'].sum()

labels = list()
for _, row in df.iterrows():
    labels.append(f'{row["Age_group"]}\n({row["Percentage"]:3.1f}%)')
    
textprops = {'ha':'center', 'va':'center'}
wedgeprops = {'linewidth':1.5, 'edgecolor':'white'}

#1
offsets = np.zeros(len(labels)); offsets[-3::] = 0.05

#2
ax.pie(x=df['Population'], labels=labels, wedgeprops=wedgeprops, 
       textprops=textprops, labeldistance=1.18, explode=offsets)

title = f'Population of the United States by age group (2022)'
subtitle = 'Source: US Census Bureau.'
set_title_and_subtitle(fig=fig, title=title, subtitle=subtitle, 
                       alignment='left', h_offset=25)

fig.savefig('charts/pie-chart-exploded.png', dpi=300, 
            bbox_inches='tight')