How to plot multiple population pyramids using for loop or facetgrid

41 Views Asked by At

I've been trying to plot a population pyramid which shows age groups as the y-axis and population on the x axis with male/female distribution as bar charts opposing each other. I've been partially successful with using a for loop but i want to display all on one singular grid and have'nt been successful, also tried facet grid with seaborn with no success

This is the code using the for loop

# Get unique years from the dataset
unique_years = ages_male_female_df['Year'].unique()

# Create pyramid charts for each year
for year in unique_years:
    df_year = ages_male_female_df[ages_male_female_df['Year'] == year]

    # Initialize the figure
    plt.figure(figsize=(10, 6))

    # Plot the male population on the left side
    sns.barplot(x=df_year['Population'], y=df_year['Age_group'], data=df_year, color='blue', label='Male')

    # Plot the female population on the right side and invert the bars
    sns.barplot(x=-df_year['Population'], y=df_year['Age_group'], data=df_year, color='pink', label='Female')

    # Set labels and title
    plt.xlabel('Population')
    plt.ylabel('Age Group')
    plt.title(f'Population Pyramid for {year}')

    # Show the legend
    plt.legend(loc='upper right')

    # Set the x-axis limits to ensure non-negative values
    plt.xlim(-50000, 50000)

    # Create a mirrored y-axis on the right side
   # plt.twinx()

    # Set labels and ticks on the right y-axis
    plt.ylabel('Age Group')

    # Display the plot for the current year
    plt.show()

and it correctly outputs each years graph but as multiple separate imagesfor loop output, how do i get it to be on the one plot like facetgrid would do, enter image description here

0

There are 0 best solutions below