I have created a horizontal bar chart of student exam score by taking in input from a file that contains the count of students in the file, and a student's last name followed by their score in each subsequent line. I am using the graphics module created by John Zelle primarily for beginners to try out a simple graphics.
The following I have written works:
- Code: Select all
# horizontal bar chart
# This program creates a horizontal bar chart of student exam scores by taking in input from a file that contains the count of students in the file, and a student's last name followed by their score (from 0 to 100) in each subsequent line.
# by: Luis Henriquez-Perez
from graphics import*
# get the input
# fname = input("Enter filename: ")
fname = 'class_sample.txt'
file = open(fname, 'r')
list1 = file.readlines()
# get the number of students in the file
students = int(list1)
# create the window
# set the coordinates so that the chart is scalable
win = GraphWin('Grade Chart', 400, 400)
win.setCoords(0, 0, 500, 500)
# access the information in the file
scores = 
names = 
for item in list1[1:]:
scores += [int(item.split())]
names += [item.split()]
# initial rectangle
rect = Rectangle(Point(140, 20), Point(140 + 3.4 * scores, 460/(students)))
# initial name
text = Text(Point(70, 230/students + 10), names)
for i in range(students-1):
rect = Rectangle(Point(140, rect.getP1().getY() + 460/students), Point(140 + 3.4 * scores[i + 1], rect.getP2().getY() + 460/students))
# create the names next to the bars
text1 = Text(Point(70, (rect.getP1().getY() + rect.getP2().getY())/2) , names[i + 1])
# wait for mouse click
It creates this image:
using a text file named 'class_sample.txt' with this information.
I have a couple concerns about this code however that I would like advice to address. First, I realize that I am drawing rectangles (or bars) twice. I create the first one outside of the for loop and all the other ones in the for loop. Since I do this work twice it becomes a bit annoying because whenever I want to change something about the bars I have to do it in two places. Second, I realize that I can make the code a lot easier to read by creating functions for creating the rectangle and maybe also for initializing the window and opening the file. As python programmers, what would you suggest I can do to make this code more readable and efficient?