Python 从数组中绘制直方图

Python 从数组中绘制直方图,python,python-3.x,matplotlib,Python,Python 3.x,Matplotlib,示例阵列: 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]) 我明白了: 如何获得不同颜色的列? 我如何得到标签,比如如果一个绿色的列,图例显示数字1是绿色的 我怀疑我可能会创建四个不同的数据集,但我无法开始工作。与其直接调用plt.hist,不如尝试使用子图并在其中绘制

示例阵列:

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])
我明白了:

如何获得不同颜色的列? 我如何得到标签,比如如果一个绿色的列,图例显示数字1是绿色的


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

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

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()
导入matplotlib.pyplot作为plt
#定义窗口大小、输出和轴
图,ax=plt.子批次(图尺寸=[8,6])
#设置绘图标题
ax.设置标题(“某些标题”)
#设置x轴名称
ax.集合标签(“X标签”)
#设置y轴名称
ax.设置标签(“Y标签”)
#在输出中创建直方图
N、 箱子,补丁=ax.hist(数据,箱子=50,color=“#777777”)#所有箱子的初始颜色
#遍历所有直方图元素
#此交互中的每个元素都是直方图上的一个面片,其中:
#-bin_size-当前bin中的记录数
#-bin-当前bin的值(x轴)
#-patch-一个矩形,对象类为matplotlib.patches.patch
#有关修补程序属性的更多详细信息:[访问此链接][1]
对于箱子大小、箱子、拉链中的补丁(N、箱子、补丁):
如果bin_size==:
patch.set_facecolor(“”)
补丁。设置标签(“某物”)
plt.show()

您的所有数据点都是整数吗?不,它会告诉我以下错误:ValueError:color kwarg每个数据必须有一种颜色。将颜色数组减少1种颜色,只有4种颜色更新了答案,请尝试。