如何在python 3中按给定点绘制直方图

时间:2019-05-08 14:35:03

标签: python matplotlib histogram

我有60个数字,分为8个间隔:

[[534, 540.0, 3], [540.0, 546.0, 3], [546.0, 552.0, 14], [552.0, 558.0, 8], [558.0, 564.0, 14], [564.0, 570.0, 9], [570.0, 576.0, 6], [576.0, 582.0, 3]]

每个间隔中的数字除以6:

[0.5, 0.5, 2.33, 1.33, 2.33, 1.5, 1.0, 0.5]

如何在根据我的间隔对间隔进行签名的同时创建直方图,以使条形的高度与获得的值相对应?结果应该是这样的

i do not have reputation to post images, so

2 个答案:

答案 0 :(得分:0)

您可以使用matplotlib

import matplotlib.pyplot as plt
data = [[534, 540.0, 3], [540.0, 546.0, 3], [546.0, 552.0, 14], [552.0, 558.0, 8], [558.0, 564.0, 14], [564.0, 570.0, 9], [570.0, 576.0, 6], [576.0, 582.0, 3]]

x = [element[0]+3 for element in data]
y = [element[2]/6 for element in data]

width = 6 
plt.bar(x, y, width, color="blue")
plt.show()

更多文档here

答案 1 :(得分:0)

运行F Blanchet的代码在我的IPython控制台中生成以下图形:

enter image description here

那看起来并不像您的图像。我认为您正在寻找类似这样的东西,其中x标记位于条之间

enter image description here

这是我用来生成上述情节的代码:

import matplotlib.pyplot as plt

# Include one more value for final x-tick.
intervals = list(range(534, 583, 6))

# Include one more bar height that == 0.
bar_height = [0.5, 0.5, 2.33, 1.33, 2.33, 1.5, 1.0, 0.5, 0]

plt.bar(intervals,
        bar_height,
        width = [6] * 8 + [0],  # Set width of 0 bar to 0.
        align = "edge",         # Align ticks at edge of bars.
        tick_label = intervals) # Make tick labels explicit.