带有千个箱子的直方图柱间距
我正在使用matplotlib的hist()
函数或bar()
来制作直方图,我想使用超过10,000个柱子(每个柱子代表一个大实体在每个坐标上的计数)。我想知道有没有办法在创建图形时让这些竖条之间有更多的空白。目前,直方图的每个柱子之间没有空白。例如:
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
来简单地扩大图的大小,但最终的结果总是每个竖条紧挨着,没有空白。
2 个回答
0
plt.hist
最终是通过 plt.bar
来绘制柱状图的,所以我们可以通过 width=
参数来调整柱子之间的间距。
fig, ax1 = plt.subplots()
ax1.hist(coordinate_counts, bins=range(1, 10000), width=0.5)
需要注意的是,和 rwidth
不同,rwidth
的柱子宽度是根据它的区间大小来决定的(这个值在 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);
55
参数 rwidth
用来设置你的柱子的宽度,相对于你的箱子的宽度来说。举个例子,如果你的 bin
宽度是1,而 rwidth=0.5
,那么柱子的宽度就是0.5。这样一来,柱子两边就会留出0.25的空隙。
需要注意的是:这样会导致相邻的柱子之间有0.5的空隙。如果你的箱子数量比较多,这些空隙可能看不出来。但如果箱子数量少的话,这些空隙就会显现出来。