[英]What is the purpose of y_pos in matplotlib
我一直在瀏覽 matplot lib 的文檔,但我不明白y_pos
的目的。 例如,為什么我不能使用fullnames
名而不是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()
樣本數據
#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)
玩了一下你的代碼。 在某種程度上,您的問題更多是關於 x-ticks 的使用:在您的情況下這不是必需的。
假設我們有四個具有相應分數的學生:
[('Beth', 'Harley', 60),
('Olivia', 'Dill', 69),
('Megan', 'Harley', 48),
('Charles', 'Laurie', 43)]
代碼中相關的三行是:
# 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)
一個更簡單的解決方案是不首先對名稱進行排序,而讓 matplotlib 做它的事情。
plt.bar(fullnames, scores, align='center', alpha=0.5,color=['b'])
# This line is deleted ==> plt.xticks(y_pos, fullnames)
結果是一樣的:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.