无法绘制直方图的箱子是分开的,xaxis值是压缩的

2024-04-20 13:00:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python的初学者。我在使用matplotlib和numpy绘制直方图时遇到了一个问题。我想研究汽车年龄范围内汽车数量的分布。我的x轴是车的年龄,而我的y轴是车的数量。以下是我的代码:

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()

这是我的错误截图。垃圾箱彼此相距很远,x轴的值被压缩在一起。这不是我想要的 enter image description here


Tags: ofnumpynumberage数量matplotlibnpplt
1条回答
网友
1楼 · 发布于 2024-04-20 13:00:18

首先,要正确显示数据,需要将number_of_car中的值转换为整数。为此,您可以在创建数组时使用dtype=int选项。你知道吗

其次,直方图已经完成,所以应该使用bar绘图:

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()

现在,为了使xticks可读,您至少有两种解决方案:

  1. 增加图形宽度,直到有足够的空间容纳所有XTick。为此,您可以在创建地物时使用figsize选项:

    fig, ax = plt.subplots(figsize=(14, 4))
    
  2. ax.tick_params('x', rotation=60)

相关问题 更多 >