【问题标题】:How can I plot Histogram for discrete data using python matplotlib? [closed]如何使用 python matplotlib 绘制离散数据的直方图? [关闭]
【发布时间】:2021-09-01 15:15:54
【问题描述】:

这是数据,如何使用 matplotlib 在此离散数据上绘制直方图。

X   F
3   3
4   3
5   5
6   3
7   4
8   4
9   3
10  4
11  2
12  2
13  3
14  1
15  2
16  5
17  2
18  1
19  2
20  1

【问题讨论】:

  • df.set_index('X').plot.bar()?
  • 这可能不是最佳的,但这里是最简单的解决方案:将值存储为:values = [x[i] for i in range(len(x)) for j in range(f[i])],并使用 hist() 模块与此值数组。 x 中的每个值 x[i] 重复 f[i] 次。
  • 因为这已经在数据框中:df.plot(kind='bar', x='X', ec='k', width=1)

标签: python pandas matplotlib statistics histogram


【解决方案1】:

您的数据已经是一个直方图(不需要在这里合并任何观察结果,对吗?),所以我想您只需要绘制它。

# First read in the data into a dataframe in this case.
data = """
3   3
4   3
5   5
6   3
7   4
8   4
9   3
10  4
11  2
12  2
13  3
14  1
15  2
16  5
17  2
18  1
19  2
20  1""".split();
data = list(map(int, data))
data = pd.DataFrame({'X': data[::2], 'F': data[1::2]})

# Use matplotlib to draw a bar chart. Draw it with histogram style.
plt.bar(data.X, data.F, align='edge', width=1, edgecolor='k');

【讨论】:

    猜你喜欢
    • 2017-12-08
    • 2013-08-21
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    • 2018-06-23
    • 2015-09-19
    • 1970-01-01
    相关资源
    最近更新 更多