在 Matplotlib 中根据预先计数的数据绘制直方图

matplotlibserver side programmingprogramming更新于 2025/8/26 6:37:17

要在 Matplotlib 中根据预先计数的数据绘制直方图,我们可以采取以下步骤 −

  • 创建一个数字列表。

  • 借助输入数据创建一个预先计数的列表。

  • 使用 hist() 方法绘制一个包含 data、color=red 和 label=data 的直方图。

  • 使用 hist() 方法绘制另一个包含 counted data、color=default 和 label=counted_data 的直方图。

  • 要放置图例,请使用 legend()方法。

  • 要显示图形,请使用 show() 方法。

示例

from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
data = [1, 2, 2, 3, 4, 5, 5, 5, 5, 6, 10]
counted_data = {1: 1, 2: 2, 3: 1, 4: 1, 5: 4, 6: 1, 10: 1}
hh = plt.hist(data, bins=len(data), rwidth=.95, color='red', label="data")
hh1 = plt.hist(counted_data.keys(), weights=counted_data.values(),
   bins=range(10), rwidth=.95, label="counted_data")
plt.legend()
plt.show()

输出


相关文章