Dinosaurius
Dinosaurius

Reputation: 8638

How to create a bar chart with non-numeric X axis?

This is my DataFrame df:

    bin             qty
0   (0.0, 25.0]     3634.805042
1   (25.0, 50.0]    1389.567460
2   (50.0, 75.0]    1177.400000
3   (75.0, 100.0]   898.750000
4   (100.0, 125.0]  763.000000

I want to create a bar chart like a histogram. Y axis should be qty and X axis should be bin, for example "(0.0, 25.0]", rotated vertically.

I tried this, but it fails because bin is not numeric:

plt.bar(df.bin, df.qty, align='center', alpha=0.5)
plt.show()

Upvotes: 4

Views: 2402

Answers (2)

Scott Boston
Scott Boston

Reputation: 153510

Let's try, using Pandas Plot:

df.plot.bar('bin','qty', alpha=.5)

Output:

enter image description here

Using matplotlib:

x = pd.np.arange(len(df['bin']))
fig,ax = plt.subplots(figsize=(14,8))
ax.bar(x,df['qty'])
width = .35
ax.set_xticks(x + width // 2)
ax.set_xticklabels(df['bin'])
plt.show()

Output:

enter image description here

Upvotes: 2

Edward Brennan
Edward Brennan

Reputation: 131

If you're trying to use matplotlib, your bin column isn't a valid object. matplotlib.pyplot.bar requires a sequence of scalars equivalent to the left value of each bin. So your dataframe should look like

        bin             qty
    0   0.0     3634.805042
    1   25.0    1389.567460
    2   50.0    1177.400000
    3   75.0     898.750000
    4   100.0    763.000000

Upvotes: -1

Related Questions