具有数千个分箱的直方图条之间的间距

问题描述 投票:0回答:2

我正在使用 matplotlib 的

hist()
函数或
bar()
制作直方图,并且我想使用 >10,000 个 bin(一个 bin 代表大型实体每个坐标处的计数)。当我创建图形时,有什么方法可以在垂直条之间创建更多空白吗?目前,直方图的每个条形之间没有空格。例如:

import matplotlib.pyplot as plt
import random

# Generating dummy data    
coordinate_counts = [random.randrange(1,10000) for __ in range(1,100000)]

# plotting
fig, ax1 = plt.subplots()
ax1.hist(coordinate_counts, bins=range(1,10000))

我尝试过使用

rwidth
并改变其值,也尝试过使用
figsize
并简单地扩大绘图的大小,但最终结果始终是每个垂直条彼此相邻,中间没有空格-之间。

python matplotlib bar-chart histogram width
2个回答
55
投票

参数

rwidth
指定条形相对于 bin 宽度的宽度。例如,如果您的
bin
宽度为 1 且
rwidth=0.5
,则条形宽度将为 0.5。栏的两侧都有 0.25 的空间。

Mind:连续柱之间的间距为 0.5。根据您拥有的垃圾箱数量,您将看不到这些空间。但随着垃圾箱的减少,它们确实出现了。

enter image description here


0
投票

plt.hist
最终使用
plt.bar
绘制条形,因此在条形之间形成间隙的另一种方法是通过
width=
参数。

fig, ax1 = plt.subplots()
ax1.hist(coordinate_counts, bins=range(1, 10000), width=0.5)

需要注意的一件事是,与

rwidth
不同,其中条形的宽度取决于其 bin 的大小(并且是 0 到 1 之间的值),
width
是确定条形宽度的绝对值(并且可以大于 1)。举个例子可能会更好地说明。以下代码

coordinate_counts = list(range(10))*10
plt.hist(coordinate_counts, bins=[0, 3, 8, 10], width=2);

绘制以下图表

同时绘制以下代码

plt.hist(coordinate_counts, bins=[0, 3, 8, 10], rwidth=0.5);

© www.soinside.com 2019 - 2024. All rights reserved.