【问题标题】:first and last bars on matplotlib histogram appear movedmatplotlib 直方图上的第一个和最后一个条出现移动
【发布时间】:2016-08-02 12:56:53
【问题描述】:

我正在尝试使用这些值创建直方图:

[1, 1, 1, 2, 2, 1, 1, 1, 1, 5, 2, 1, 1, 2, 2, 1, 1, 4, 1, 1, 2, 1, 1, 2]

我使用的代码是这样的

plt.hist(values, histtype='bar', color='green', alpha=0.5)
plt.title(library_name, fontsize=12)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
x1, x2, y1, y2 = plt.axis()
plt.axis((x1-0.5, x2+0.5, y1, y2+0.05))
plt.savefig("../results/histograms/" + library_name)

我得到了这个直方图

有谁知道为什么第一个和最后一个小节看起来除了 xtick 之外?我尝试使用 plt.margins 函数但没有结果。

非常感谢

【问题讨论】:

  • matplotlib 分箱是非常自动的,并且对您的意图毫不在意。默认情况下,它会在最小值和最大值之间创建 10 个 bin。因此,在许多情况下,您必须手动指定垃圾箱(如 Samuel Bancroft 的回答)

标签: python matplotlib histogram


【解决方案1】:

要获得居中对齐而不是左对齐的 bin,请使用 plt.hist(data, bins=np.arange(50)-0.5)

示例代码:

import matplotlib.pyplot as plt
import numpy as np

values = [1, 1, 1, 2, 2, 1, 1, 1, 1, 5, 2, 1, 1, 2, 2,5,3,2,5, 1, 1, 4, 1, 1, 2, 1, 1,7,8,9,9,3,8,6, 2]

offset = 0.5

plt.hist(values,  bins=np.arange(1,np.max(values)+2)-offset, histtype='bar', color='green', alpha=0.5)
plt.title('library_name', fontsize=12)
plt.xlabel('xlabel')
plt.ylabel('ylabel')
x1, x2, y1, y2 = plt.axis()
plt.axis((x1-0.5, x2+0.5, y1, y2+0.05))
plt.show()

【讨论】:

  • 谢谢@Samuel Bancroft。有没有办法在不指定直方图中条形的恒定最大值的情况下做到这一点(在本例中为 7)?我希望它尽可能通用。
  • 没问题。我已经更新了代码,使其对您来说更通用。希望对您有所帮助!
【解决方案2】:

顺便说一句,您可以使用 [免责声明:我写的]“physt”库,它有几个分箱选项,包括一个适用于整数的选项 - 请参阅 https://github.com/janpipek/physt,特别是你的情况http://nbviewer.jupyter.org/github/janpipek/physt/blob/master/doc/Binning.ipynb#Integer-binning

代码如下:

import physt
h = physt.histogram(values, "integer")
ax = h.plot(color="green", alpha=0.5, ticks="center")

...然后添加您的轴/plt 格式...

【讨论】:

  • 谢谢,看起来不错
猜你喜欢
  • 2016-06-23
  • 2020-07-17
  • 2014-07-18
  • 1970-01-01
  • 2018-05-28
  • 1970-01-01
  • 1970-01-01
  • 2017-02-08
  • 1970-01-01
相关资源
最近更新 更多