0

can you help me with the following task?

I need an output like this: https://prnt.sc/11e7rcq (of course the color is not important, is just an example about my desired result)

But I get another output.. My result is in the code, what is the error made?

df = pd.DataFrame(
    {
        'pension': [0,0,1,1],
        'sex': ['female','male','female','male'],
        'count': [2,3,3,1]
    }
)
labels = df['sex'].tolist()
count = df['count'].tolist()
pension = df['pension'].tolist()

x = np.arange(len(labels))  # the label locations
width = 0.35  # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, count, width, label='Men')
rects2 = ax.bar(x + width/2, pension, width, label='Women')

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()

ax.bar_label(rects1, padding=3)
ax.bar_label(rects2, padding=3)

fig.tight_layout()

plt.show()

1 Answer 1

2

You can do as below:

import seaborn as sns
pension = [0,0,1,1]
count = [2, 3,3,1]
sex = ['female','male','female','male',]
df = pd.DataFrame({'pension': pension,
                    'count': count,
                  "sex": sex})

sns.barplot(x="sex", y="count", hue="pension", data=df)

Result will be as below:

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Just for curiosity, is possible get this with matplotlib?
Yes, it should be. But I guess we need to group df by sex and pension if we want to get this with matplotlib.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.