0

I am trying to create a population pyramid grouped by gender. Unfortunately, I can't get this to work. The plot is just a white picture and the axes seem to be reversed somehow. Maybe someone can help me, thank you.

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# I read this testdata from a csv file
testdata = pd.DataFrame({'age': [20, 20, 21, 21, 22, 22, 23, 23],
                'gender': ["male", "female", "male", "female", "male", "female", "male", "female"],
                'count': [10, -12, 13, -10, 16, -14, 17, -16]});


plt.figure(figsize=(13, 10), dpi=80)
group_col = 'gender'
order_of_bars = testdata['age'].unique()[::-1]
colors = [plt.cm.Spectral(i / float(len(testdata[group_col].unique()) - 1)) for i in range(len(testdata[group_col].unique()))]


for c, group in zip(colors, testdata[group_col].unique()):
    barplot = sns.barplot(x='count', y='age', data=testdata.loc[testdata[group_col] == group, :], order=order_of_bars, color=c, label=group)

plt.xlabel("Counts")
plt.ylabel("Age")
plt.yticks(fontsize=12)
plt.title("Pyramide", fontsize=22)
plt.legend()
plt.show()
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
René Winkler
  • 6,508
  • 7
  • 42
  • 69

1 Answers1

1

If you are looking for this population pyramid, let's try:

sns.barplot(data=testdata, x='count',y='age',
            hue='gender',orient='horizontal', 
            dodge=False)

Output:

enter image description here

Quang Hoang
  • 146,074
  • 10
  • 56
  • 74