使用 Pylab 绘制直方图
使用 Python 2.7 工作。
我正在尝试为随机游走 50 次运行生成的数字绘制直方图。但是当我使用 pylab.hist(batting_average, bins = 10) 时,我得到一个奇怪的多色直方图,它上升到接近 500,但只有 50 次步行,它应该能够在 y 上运行的最大值-axis 将为 50。
这是我的代码:
a = ['Hit', 'Out']
b = [.3, .7]
def battingAverage(atBats, some_list=a, probabilities=b):
num_hits = 0
num_outs = 0
current_BA = []
for i in range(1,atBats):
if random_pick(a, b) == 'Hit':
num_hits += 1
else:
num_outs +=1
BA = float(num_hits)/(float(num_hits)+float(num_outs))
current_BA.append(BA)
return current_BA
def printBAs():
for i in range(50):
batting_average = battingAverage(501)
pylab.hist(batting_average, bins=10)
我的直方图出了什么问题!?
如果有任何事情需要澄清,请告诉我,我会尽力而为。
Working in Python 2.7.
I'm trying to plot a histogram for the numbers generated by 50 run-throughs of my random walk. But when I use pylab.hist(batting_average, bins = 10), I get a weird multi-colored histogram that goes up close to 500, but with only 50 runs of the walk, the maximum it should be able to go on the y-axis would be 50.
Here's my code:
a = ['Hit', 'Out']
b = [.3, .7]
def battingAverage(atBats, some_list=a, probabilities=b):
num_hits = 0
num_outs = 0
current_BA = []
for i in range(1,atBats):
if random_pick(a, b) == 'Hit':
num_hits += 1
else:
num_outs +=1
BA = float(num_hits)/(float(num_hits)+float(num_outs))
current_BA.append(BA)
return current_BA
def printBAs():
for i in range(50):
batting_average = battingAverage(501)
pylab.hist(batting_average, bins=10)
What's wrong with my histogram!?
Let me know if anything needs clarification, and I'll do my best.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
传递给
battingAverage
的参数是 501...,是击球数。您正在制作 50 个直方图,每个直方图有 500 个击球数。(哦,你需要修复代码的格式......缩进被搞乱了。)
你的代码没有按照你想象的那样做。
我认为您希望
battingAverage
返回最终的击球平均值,但它返回一个击球平均值列表,每个击球都有一个。然后你就可以绘制该列表了。
我认为您想要从 battingAverage 返回单个数字,并且想要在 printBAs() 函数中累积列表,并将 pylab.hist 移出 for 循环。
我想这不是作业吧?
换句话说,我认为你想要这样的东西:
虽然该代码仍然需要清理......
The argument passed to
battingAverage
is 501... and is the number of at-bats. You're doing 50 histograms with 500 at-bats per histogram.(Oh, and you need to fix the formatting of your code... the indentation is messed up.)
Your code doesn't do what you think it does.
I think you're wanting
battingAverage
to return the final batting average, but it returns a list of batting averages, one for each at-bat.Then you're plotting that list.
I think you want to return a single number from battingAverage, and you want to accumulate the list in the printBAs() function, and move pylab.hist out of the for loop.
I don't suppose this is homework?
In other words, I think you want something like this:
Though that code still needs cleanup...