Capt_Bender
Capt_Bender

Reputation: 91

How do I create a Matplotlib bar chart with categories?

I'm trying to create a matplotlib bar chart with categories on the X-axis, but I can't get the categories right. Here's a minimal example of what I'm trying to do.

data = [[46, 11000], [97, 15000], [27, 24000], [36, 9000], [9, 17000]]
df = pd.DataFrame(data, columns=['car_id', 'price'])

fig1, ax1 = plt.subplots(figsize=(10,5))
ax1.set_title('Car prices')
ax1.bar(df['car_id'], df['price'])
plt.xticks(np.arange(len(df)), list(df['car_id']))
plt.legend()
plt.show()

enter image description here

I need the five categories (car_id) on the X-axis. What Am I doing wrong? :-/

Upvotes: 3

Views: 7450

Answers (2)

Liris
Liris

Reputation: 1511

You got confused in the xticks with the label and position. Here you specify the position np.arange(len(df)) and the labels list(df['car_id']. So he puts the labels at the specified position list(df['car_id'], i.e. array([0, 1, 2, 3, 4]).

If the position and the labels are here the same, just replace plt.xticks(np.arange(len(df)), list(df['car_id'])) by plt.xticks(df['car_id']).

If you want them to be evenly spaced, your approach is right but you also need to change ax1.bar(df['car_id'], df['price']) toax1.bar(np.arange(len(df)), df['price']), so that the bar x-position is now evenly spaced.

Full code:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np 

data = [[46, 11000], [97, 15000], [27, 24000], [36, 9000], [9, 17000]]
df = pd.DataFrame(data, columns=['car_id', 'price'])

fig1, ax1 = plt.subplots(figsize=(10,5))
ax1.set_title('Car prices')
ax1.bar(np.arange(len(df)), df['price'])
ax1.set_xticks(np.arange(len(df)))
ax1.set_xticklabels(df['car_id'])
plt.show()

enter image description here

Upvotes: 2

Quang Hoang
Quang Hoang

Reputation: 150825

You can turn car_id into category:

df['car_id'] = df['car_id'].astype('category')

df.plot.bar(x='car_id')

Output:

enter image description here

You can also plot just the price column and relabel:

ax = df.plot.bar(y='price')
ax.set_xticklabels(df['car_id'])

Upvotes: 3

Related Questions