0

I have two parallel series of data, for which I want to make a bar chart with multiple columns. I understand the idea is to shift each column by adding the width the x axis, but what if the axis consists in strings (categorical variables)?

Let's assume this is a pandas dataframe df:

+----------+------+------+
| Category | Val1 | Val2 |
+----------+------+------+
| A        |    1 |    3 |
| B        |    4 |    6 |
| C        |    6 |    7 |
| D        |    3 |    9 |
+----------+------+------+

Obviously, this will raise an error:

import matplotlib.pyplot as plt
width = 0.4
fig, ax = plt.subplots()
ax.bar(x=df['Category'], height=df['Val1'], width=width)
ax.bar(x=df['Category']+width, height=df['Val2'], width=width)

You can't add a numeral to a string.

So, what's the solution to get something like this: bar chart

mrgou
  • 1,576
  • 2
  • 21
  • 45

1 Answers1

4

You could use pandas plot function:

fig, ax = plt.subplots()
df.plot.bar(x='Category', ax=ax)

Output:

enter image description here

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