import matplotlib.pyplot as plt
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()

df['labels'] = (df['Age_group'] + ' ' + 
                df['Percentage'].map('({:3.1f}%)'.format))
    
textprops = {'ha':'center', 'va':'center'}
wedgeprops = {'linewidth':1.5, 'edgecolor':'white'}

#1
ax.pie(x=df['Population'], labels=None, wedgeprops=wedgeprops, 
       textprops=textprops)

#2
fig.legend(labels=df['labels'].to_list(), title='Age group', 
           bbox_to_anchor=(1,0.5), loc='center right',
           frameon=False)

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=120)

fig.savefig('charts/pie-chart-side-legend.png', dpi=300, 
            bbox_inches='tight')