Какова цель y_pos в matplotlib - PullRequest
0 голосов
/ 19 июня 2020

Я просматривал документацию для библиотеки matplot, но не понимаю, зачем нужна 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()

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)

1 Ответ

0 голосов
/ 20 июня 2020

Поигрался с вашим кодом. Ваш вопрос, в некотором смысле, больше касается использования 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)

Результат тот же:

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...