频率直方图,用于循环

时间:2018-10-17 13:18:00

标签: python histogram

所以我会直接说清楚。我正在尝试制作一个从文本文档中获取数字并生成频率直方图(0-10)的直方图。如果不使用for循环,则可以使它起作用,但是效果很差。这是我目前拥有的:

from graphics import *
import math

def main():

 #saying what the program does
 print("This is a program that reads a test file of test scores (0-10)")
 print("and draws a histogram with the amount of students with that score")
 print("raising the bar by one for each student.")

 #Get the name of the files with the scores
 fileInput = input("Enter the file name with the scores: ")

 #open the file with the scores and read the first line to get the # of students
 infile = open(fileInput, "r")
 stuNum = int(infile.readline())
 lineRead = infile.readlines()

 #Creates a window using the amount of students to base the height
 win = GraphWin("These Students Failed", 400, 400)
 win.setCoords(0,0,100,20)

 #Create list to hold number of each score
 scoreList = [0,0,0,0,0,0,0,0,0,0,0]

 #Create loop for each line in the file
 for line in lineRead:
     line = int(line)
     scoreList[line] += 1

 #create initial bar  
 x = 0
 height = scoreList[x]
 bar = Rectangle(Point(0,0),Point(15, height))
 bar.setFill("green")
 bar.setWidth(2)
 bar.draw(win)


 #create loop for drawing bars  
 for i in range(10):
     height = scoreList[x+1]
     bar = Rectangle(Point((15*x),0), Point((15*x), height))
     bar.setFill("green")
     bar.setWidth(2)
     bar.draw(win)


 main()

因此,除了for循环外,其他所有东西都起作用。另外,我试图做到这一点而没有额外的导入(除了数学和图形)。

这是我从中获取数字的文本文档的样子:

Text Document

所以每个条的高度是数字出现的次数。

谢谢!

1 个答案:

答案 0 :(得分:0)

#Create initial bar for students who got zero
x = 0
y = 15
height = scoreList[x]
bar = Rectangle(Point(0,0),Point(15, height))
bar.setFill("green")
bar.setWidth(2)
bar.draw(win)


#create loop for drawing bars  
for i in range(11):

    #store x as itself +1 so it goes up 1 each loop
    x = x + 1

    #have y as iteself +15 so it goes up 15 each loop
    y = y + 15

    #the height is equal to however many times the number occured in scoreList
    height = scoreList[x]

    #Create the bar based off of the first bar and the height
    bar = Rectangle(Point(y-15,0), Point((y), height))

    bar.setFill("green")
    bar.setWidth(2)
    bar.draw(win)

我有一个新的循环,可以很好地打印它们,但是我发现height = scoreList[x]的索引超出范围错误,但这似乎并没有影响程序。