gpt4 book ai didi

python - 从数组绘制直方图

转载 作者:太空宇宙 更新时间:2023-11-04 01:04:54 30 4
gpt4 key购买 nike

示例数组:

a=np.array([1,2,3,4,4,4,2,1,1,1,1])

我想从数组创建直方图,如果我使用 matplotlib.pyplot 的直方图:

import matplotlib.pyplot as plt
plt.hist(a,bins=[1,2,3,4,5])

我明白了:

number of x

如何获得不同颜色的列?以及我如何获得标签,例如如果绿色列的图例显示数字 1 是绿色的。

我怀疑我可能会创建四个不同的数据集,但我无法开始工作..

最佳答案

与其直接调用 plt.hist,不如尝试使用 subplot 并在其中绘制直方图,如下所示 -

import matplotlib.pyplot as plt
# define window size, output and axes
fig, ax = plt.subplots(figsize=[8,6])

# set plot title
ax.set_title("Some title")

# set x-axis name
ax.set_xlabel("X-Label")

# set y-axis name
ax.set_ylabel("Y-Label")

# create histogram within output
N, bins, patches = ax.hist(data, bins=50, color="#777777") #initial color of all bins

# Iterate through all histogram elements
# each element in this interation is one patch on the histogram, where:
# - bin_size - number of records in current bin
# - bin - value of current bin (x-axis)
# - patch - a rectangle, object of class matplotlib.patches.Patch
# more details on patch properties: [visit this link][1]
for bin_size, bin, patch in zip(N, bins, patches):
if bin_size == <some number>:
patch.set_facecolor("<some color like #FF000>")
patch.set_label("something")
plt.show()

关于python - 从数组绘制直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30886364/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com