1

I am trying to create a bar plot using pandas. I have the following code:

import pandas as pd

indexes = ['Strongly agree', 'Agree', 'Neutral', 'Disagree', 'Strongly disagree']

df = pd.DataFrame({'Q7': [10, 11, 1, 0, 0]}, index=indexes)
df.plot.bar(indexes, df['Q7'].values)

By my reckoning this should work but I get a weird KeyError: 'Strongly agree' thrown at me. I can't figure out why this won't work.

2
  • df.plot(kind='bar') or df.plot.bar() Commented Dec 13, 2017 at 5:03
  • Isn't plot.bar just an alias for the same? Commented Dec 13, 2017 at 5:06

1 Answer 1

2

By invoking plot as a Pandas method, you're referring to the data structures of df to make your plot.

The way you have it set up, with index=indexes, your bar plot's x values are stored in df.index. That's why Wen's suggestion in the comments to just use df.plot.bar() will work, as Pandas automatically looks to use df.index as the x-axis in this case.

Alternately, you can specify column names for x and y. In this case, you can move indexes into a column with reset_index() and then call the new index column explicitly:

df.reset_index().plot.bar(x="index", y="Q7")

Either approach will yield the correct plot:

plot

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

2 Comments

Ok thanks. And if I want to colour each bar differently?
Pandas isn't designed to support multiple colors for a single column. (And in general it's often unnecessary, and even confusing, to encode color as a redundant dimension for a categorical axis.) Still, there's a workaround here, if you really need it: stackoverflow.com/a/44495136/2799941.

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.