Issue
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()
Solution
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:
Answered By - Quang Hoang
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.