Reputation: 1064
I am a beginner in Python. I encountered a problem while plotting a histogram using matplotlib and numpy. I want to study the distribution between the number of cars within the range of the age of car. My x-axis is age_of_car, while my y-axis is number_of_car. Below are my codes:
age_of_car = np.array(['0-<1', '1-<2', '2-<3', '3-<4', '4-<5',
'5-<6', '6-<7', '7-<8', '8-<9', '9-<10','10-<11',
'11<12', '12-<13','13-<14', '14-<15', '15-<16',
'16-<17', '17-<18','18-<19', '19-<20', '20->'])
number_of_car = np.array(['91614', '87142', '57335', '28392',
'21269', '26551', '27412', '41142', '68076', '88583',
'28487', '28439', '8728', '1557', '458', '179',
'423', '444', '421', '410', '5194'])
num_bins = 20
plt.hist([age,number],num_bins)
plt.show()
Here is a screenshot of my error. The bins are spread far apart from one another and the x-axis values are cramped together. This is not what i want
Upvotes: 0
Views: 731
Reputation: 16169
First, to correctly display your data, you need to convert the values in number_of_car
to integers. For that you can use the dtype=int
option when creating the array.
Secondly, your histogram is already done so you should use a bar
plot:
from matplotlib import pyplot as plt
import numpy as np
age_of_car = np.array(['0-<1', '1-<2', '2-<3', '3-<4', '4-<5',
'5-<6', '6-<7', '7-<8', '8-<9', '9-<10','10-<11',
'11<12', '12-<13','13-<14', '14-<15', '15-<16',
'16-<17', '17-<18','18-<19', '19-<20', '20->'])
number_of_car = np.array(['91614', '87142', '57335', '28392',
'21269', '26551', '27412', '41142', '68076', '88583',
'28487', '28439', '8728', '1557', '458', '179',
'423', '444', '421', '410', '5194'], dtype=int)
fig, ax = plt.subplots()
ax.bar(age_of_car, number_of_car)
fig.tight_layout()
plt.show()
Now, to make the xticks readable, you have at least two solutions:
Increase the figure width until there is enough space for all xticks. For that you can use the figsize
option when creating the figure:
fig, ax = plt.subplots(figsize=(14, 4))
Rotate the xticks with ax.tick_params('x', rotation=60)
Upvotes: 1