I have been browsing the documentation for matplot lib, but I don't understand the purpose of y_pos
. For example, why can't I use fullnames
instead of y_pos
?
def CreateScoreBarChart(subject):
#Get all the names and scores for that subject
GetScoresSQL="""SELECT firstname,secondname,score FROM students WHERE subject=%s"""
mycursor.execute(GetScoresSQL,(subject,))
myresults = mycursor.fetchall()
fullnames = []
scores = []
for person in myresults:
fullname=person[0]+" "+person[1]
fullnames.append(fullname)
scores.append(person[2])
y_pos = sorted(fullnames)
plt.bar(y_pos, scores, align='center', alpha=0.5,color=['b'])
plt.xticks(y_pos, fullnames)
plt.ylabel('Score')
plt.xlabel('Full Name')
plt.title(subject+"'s Class Scores")
plt.show()
Sample Data
#Function to populate database
def RandomStudentMaker(NoOfStudents):
studentFNames = ["Alex","Brad","Diane","Jimmy","Logan","Harry","Susan","Olivia","Beth","Amy","Charles","Megan","Gareth","Tony"]
studentSNames=["Gaston","Leslie","Copeland","Smith","Dill","Brown","Rowan","Austin","Harley","Eakin","Colgan","Fry","Cook","Laurie"]
subjectNames=["Chemistry","Biology","Computer Science"]
insertStudentSQL="INSERT INTO students (firstname,secondname,subject,score) VALUES(%s,%s,%s,%s)"
for i in range(0,NoOfStudents):
print("here")
mycursor.execute(insertStudentSQL,(random.choice(studentFNames),random.choice(studentSNames),random.choice(subjectNames),random.randint(0,100)))
mydb.commit()
RandomStudentMaker(20)
Played a bit with your code. Your question, in a way, is more about the use of x-ticks: which isn't necessary in your case.
Assume we have four students with the corresponding scores:
[('Beth', 'Harley', 60),
('Olivia', 'Dill', 69),
('Megan', 'Harley', 48),
('Charles', 'Laurie', 43)]
The relevant three lines in your code are:
# fullname = ['Beth Harley', 'Olivia Dill', 'Megan Harley', 'Charles Laurie']
y_pos = sorted(fullnames)
# y_pos = ['Beth Harley', 'Charles Laurie', 'Megan Harley', 'Olivia Dill']
# at this point, the order of items in y_pos doesn't match the order of
# items in scores
plt.bar(y_pos, scores, align='center', alpha=0.5,color=['b'])
# here, you're rearranging the labels on the x-axis to match the right order
# of students
plt.xticks(y_pos, fullnames)
A simpler solution would be not to sort the names in the first place, and just let matplotlib do its thing.
plt.bar(fullnames, scores, align='center', alpha=0.5,color=['b'])
# This line is deleted ==> plt.xticks(y_pos, fullnames)
The result is the same:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.