【问题标题】:Trouble plotting histogram Bins are separated and the x-axis values are cramped绘制直方图问题 分箱分离且 x 轴值狭窄
【发布时间】:2018-12-11 16:21:39
【问题描述】:

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

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

这是我的错误的屏幕截图。这些 bin 彼此相距很远,x 轴值被挤在一起。这不是我想要的

【问题讨论】:

  • 您的数据中已经有了直方图。您不应该从已经过直方化的数据中计算出另一个直方图。另外,请注意您的 number_of_car 是一个字符串数组。
  • @ImportanceOfBeingErnest 您好,先生,我不清楚您的意思。您能否详细说明并指导我?既然你说我已经有了“直方图数据”。我该如何绘制它?
  • 通常人们为此使用条形图。

标签: python numpy matplotlib


【解决方案1】:

首先,要正确显示您的数据,您需要将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. 增加图形宽度,直到有足够的空间容纳所有 xticks。为此,您可以在创建图形时使用figsize 选项:

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

【讨论】:

  • 嗨,这个答案完美!如果我再问一个问题可以吗?我知道有不同的方法来绘制图表。我目前只是在使用 plt.bar(age,number,width=1.0,edgecolor="black")。但是从您的回答来看,您正在使用子图。方法之间有区别吗?您推荐我使用哪种方法?
  • @Issaki ax.barplt.bar 的区别在于第一个显示在子图ax 中的图,而plt.bar 显示在当前子图中的图(最后一个创建的) 或创建一个,如果尚不存在。如果您只有一个带有单个子图的图形,您可以坚持您的方法,但我使用的方法更适合包含多个子图的复杂图形,而且它更多。另请参阅stackoverflow.com/questions/43482191/…
猜你喜欢
  • 2018-12-12
  • 1970-01-01
  • 2011-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-27
  • 2021-10-29
  • 1970-01-01
相关资源
最近更新 更多