2

I currently have a dataframe (df) which looks like this: and I need to graph it so it looks like this:

![Desired graph][2]

Where in the graph, the columns are 'index', the blue bars are 'Total' and orange bars are 'Total.1'

And every time I've tried to do it I get KeyErrors, can someone PLEASE point me in the right direction because I feel like I've tried everything but something always goes wrong

0

1 Answer 1

3

To generate a simple horizontal stacked bar chart is easy, the below code will accomplish the task.

df.set_index('index').plot(stacked=True, kind='barh')
plt.tight_layout()
plt.show()

However, since your labels are so long, the layout will cut off information, and you may want to pre-process your labels so they look better.


Here is what I would recommend in terms of plot format:

options = {
    'stacked': True,
    'kind': 'barh',
    'title': 'Medals at the Winter and Summer Olympics'
}

df.rename(columns={'Total': 'Winter Games', 'Total.1': 'Summer Games'}).assign(
    code=df['index'].str.extract(r'\((.*?)\)')
).set_index('code')[['Winter Games', 'Summer Games']].plot(**options)

plt.show()

Which results in:

enter image description here

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

9 Comments

When you say fiddle with the massive country labels and add a column for abbreviation, can the column just be numbers 0...x?
How are you getting it to display the two colours? mine is just coming up as one big blue bar
The bar has the correct values, but in the top right hand corner my key is only displaying Total.1
Are you sure you're indexing both columns?
Yup I used the same .set_index('code')[['Total', 'Total.1']] as you
|

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.