是否有一个参数可以在matplotlib中使用指定位置稍微调整一下?

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

我正在使用plt.bar函数绘制直方图。

arr = [1, 1, 2, 2, 2, 5, 5, 3]
hist, bin_edges = np.histogram(arr, bins = range(7))
plt.bar(bin_edges[:-1], hist)
plt.xlim(min(bin_edges), max(bin_edges))
plt.show()

enter image description here

每个条形正好位于刻度线的中间(1,2,...,5),这并不表示边缘明显包括左侧,不包括右侧,除了最后一个边缘。

param width用于设置bar的宽度,而不是位置。

是否有一个参数可以在matplotlib中将每个条形图放置一点指定的位置(例如0.5)?

python matplotlib
2个回答
0
投票

你有三个选择。您可以选择最合适且易于理解的任何一种。

选项1:将条形中心(x位置)向左移动(-0.5)或向右移动(+0.5),然后将x-ticks设置为0.5,1.5,2.5,依此类推

arr = [1, 1, 2, 2, 2, 5, 5, 3]
hist, bin_edges = np.histogram(arr, bins = range(7))
plt.bar(bin_edges[:-1]-0.5, hist)
plt.xlim(min(bin_edges), max(bin_edges))
plt.ticks(bin_edges[:-1]-0.5)
plt.show()

enter image description here

选项2:使用align=edge,默认情况下会对齐刻度线的右边并假设一些默认厚度(如下图所示为0.8)

plt.bar(bin_edges[:-1], hist, align='edge')

enter image description here

选项3:使用具有定义宽度的align=edge(正宽度将对齐到右侧,负宽度将对齐到左侧)

plt.bar(bin_edges[:-1], hist, align='edge', width=-0.5)

enter image description here


0
投票

你想使用bar(x, y, align='edge')

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