大佬教程收集整理的这篇文章主要介绍了如何制作按特定步骤分隔范围的 mathplotlib 直方图?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我想制作一个显示成绩的直方图(例如),并且我希望能够给 mathplotlib 一个特定的步长,以使 bin 范围从它开始。
例如,如果给定的步长为 16,我希望直方图如下所示: Example
我尝试这样做:
def custom_histogram(lst,high_bound,low_bound,step):
bounds_dif = high_bound-low_bound
if bounds_dif%step == 0:
bin = int((high_bound-low_bound)/step)
else:
bin = int((high_bound-low_bound)/step) + 1
plt.hist(lst,bin,ec="white")
plt.show()
但是然后范围被平均划分,而不是作为步骤(例如最后一个 bin 不是 96-100)。
在 matplotlib documentation 中,它说:
如果bins是一个序列,它定义了bin的边缘,包括第一个bin的左边缘和最后一个bin的右边缘;在这种情况下,bin 的间距可能不等。除了最后一个(最右边的)垃圾箱外,所有垃圾箱都是半开的。
这样你就可以:
# The first and last bins will be inclusive
bins = list(range(0,max(lst),step) + [max(lst)]
plt.hist(lst,bins,ec="white")
如果您想保留保留自定义边界的可能性:
bins = list(range(low_bound,high_bound,step)) + [high_bound]
plt.hist(lst,ec="white")
最后一条可能比其他条更细。诀窍是应用与另一个条相同的宽度。
# We need to get the Axe. This is one solution.
fig,ax = plt.subplots()
bins = list(range(low_bound,step)) + [high_bound]
ax.hist(lst,ec="white")
# Applies the width of the first Rectangle to the last one
ax.patches[-1].set_width(ax.patches[0].get_width())
之前:
之后:
以上是大佬教程为你收集整理的如何制作按特定步骤分隔范围的 mathplotlib 直方图?全部内容,希望文章能够帮你解决如何制作按特定步骤分隔范围的 mathplotlib 直方图?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。