使用列表创建直方图条形图

时间:2018-01-31 22:37:29

标签: python python-3.x histogram

首先让我说我知道直方图函数,它只是从数据列表中创建一个漂亮的直方图。对于这个项目,我试图用一些有点难的方式做所有事情,因为就我而言,更多的代码=更多的练习。

现在问题的关键在于,在我提供了大量帮助的情况下,我设法编写了提取数据集的代码,获取用户输入的标题和数量的垃圾箱,并将所有内容准确地收集到“直方图”列表中,类似于[1,3,5,3,1],其数字与一系列数据的频率相对应。

从这一点开始我要做的是获取直方图列表并使用plt.bar()将其放在条形图中。我对plt.scatter()有一定的了解,但看起来栏的作用与

不同
plt.bar(x, y, align='center')
plt.xticks(y)
plt.show

x是包含bin的分隔值的列表,y是频率列表,只返回一个空图。任何帮助将不胜感激。

编辑:代码修改:

column="voltage"
y=[14, 5, 5, 4, 3, 5, 5, 4, 6, 9] # frequencies
x=[-4.9183599999999998, -3.916083, -2.9138060000000001, -1.9115290000000003, 
-0.90925200000000039, 0.093024999999999025, 1.0953019999999993, 
2.0975789999999996, 3.0998559999999991, 4.1021329999999985, 
5.1044099999999979] #bin limits
z=range(len(y))
plt.bar(z, y, 1.0)
plt.xlabel("%s" %column)
plt.xticks(z, x)
plt.show()

产生:

enter image description here

非常接近,最终我需要围绕x,但在此之前,我如何让刻度线向右对齐?另外,为什么xlabel行输出“1”而不是字符串?

1 个答案:

答案 0 :(得分:1)

show遗漏了一些() - 你的代码不符合mvce的条件。

这有效:

import matplotlib.pyplot as plt

y = [1,1,4,7,4,3]

x = range(len(y))

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

bar plot 1

你的y和x有不同的尺寸,它们会被裁剪成较短的尺寸。

import matplotlib.pyplot as plt

column="voltage"
y=[14, 5, 5, 4, 3, 5, 5, 4, 6, 9] # frequencies
x=[-4.9183599999999998, -3.916083, -2.9138060000000001, -1.9115290000000003, 
-0.90925200000000039, 0.093024999999999025, 1.0953019999999993, 
2.0975789999999996, 3.0998559999999991, 4.1021329999999985, 
5.1044099999999979] #bin limits
z=range(len(y))

plt.bar(z, y, 0.8)
plt.xlabel("%s" %column) 

plt.xticks(z,[str(round(i,4)) for i in x], rotation=35) # round, label and use

plt.show()

bar plot 2

我在弹出窗口中调整了子画面边框,你需要对其进行编码。如何以及如何将所有条形向右移动使它们位于刻度线之间,请参阅:

Move graph position within plot (matplotlib)

对我来说太多了matplotmagic。