如何在Matplotlib中手动指定bin?

2024-05-04 19:03:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据包含各种波动性值,即0到1之间的十进制数。现在,只有6%到24%之间的值是特别相关的,所以我试图建立一个直方图来显示这些值的相对计数。我想要一个有0-6%,6-8%的箱子的柱状图。。。22-24%,&24%,但事实证明这是非常困难的。总共应该有11个箱子,箱子的标签应该在箱子下面的中央。y轴不能有任何标签,因为只有相对计数很重要,而且包括y轴上的值会降低我要强调的相对性。在

我几乎可以通过阅读Matplotlib xticks not lining up with histogram和{a2}这样的答案来做到这一点。在

如果有人能帮我解决这个问题,我将不胜感激。谢谢你的帮助。在

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.path as path

graph1, ax = plt.subplots()

n, bins = np.histogram(values, 11)

left = np.array(bins[:-1])
right = np.array(bins[1:])
bottom = np.zeros(len(left))
top = bottom + n

XY = np.array([[left, left, right, right], [bottom, top, top, bottom]]).T

barpath = path.Path.make_compound_path_from_polys(XY)

patch = patches.PathPatch(barpath, facecolor="blue", edgecolor="#FFFFFF", 
alpha = 0.75)
ax.add_patch(patch)

ax.set_xlim(left[0], right[-1])
ax.set_ylim(bottom.min(), top.max())

graph1.suptitle("1-Year Rolling Volatilities")
ax.axes.get_yaxis().set_visible(False)

plt.show()

这将生成几乎正确的柱状图,但是存储箱不是我想要的间隔,xtick不是居中的,并且每个箱子没有一个标签。在


Tags: pathimportrightmatplotlibtopasnpplt
1条回答
网友
1楼 · 发布于 2024-05-04 19:03:42
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.path as path

graph1, ax = plt.subplots()

values = [0.15, 0.23, 0.061, 0.085, 0.06, 0.09, 0.07, 0.05, 0.04, 0.08]
#n, bins = np.histogram(values, 11)
plt.hist(values, bins=[0, 0.06, 0.08, 0.22, 0.24, 1.00])

你也可以用这样的方法来设置你的垃圾箱下面的勾号。有关在此堆栈溢出后设置刻度的详细信息Matplotlib - label each bin

相关问题 更多 >