对于一个项目,我写了一个代码,学生可以在其中输入自己的姓名、录取号、数学、物理和化学成绩。现在我想要一个条形图来比较他的得分和最高得分手。我定义了一个列表(l_math、l_chem和l_phy(,它是所有学生的所有分数的列表。我甚至将最大分数定义为:max_math、max_chem和max_phy。。。
我试着使用pandas并更改Charles Landau编写的代码:
import random
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
s = "Crime Type Summer|Crime Type Winter".split("|")
# Generate dummy data into a dataframe
j = {x: [random.choice(["ASB", "Violence", "Theft", "Public Order", "Drugs"]
) for j in range(300)] for x in s}
df = pd.DataFrame(j)
index = np.arange(5)
bar_width = 0.35
fig, ax = plt.subplots()
summer = ax.bar(index, df["Crime Type Summer"].value_counts(), bar_width,
label="Summer")
winter = ax.bar(index+bar_width, df["Crime Type Winter"].value_counts(),
bar_width, label="Winter")
ax.set_xlabel('Category')
ax.set_ylabel('Incidence')
ax.set_title('Crime incidence by season, type')
ax.set_xticks(index + bar_width / 2)
ax.set_xticklabels(["ASB", "Violence", "Theft", "Public Order", "Drugs"])
ax.legend()
plt.show()
但我不知道如何修改此代码以满足我的需求。。。
任何帮助都将不胜感激!!
只需修改您发布的代码,就可以完成任务:
import random
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# assuming math, chem, physics ()
student_scores = [9, 1.5, 4.6]
max_score = [9.1, 8.5, 7.8]
df = pd.DataFrame({
'student_scores': student_scores,
'max_score': max_score
})
index = np.arange(len(df))
bar_width = 0.35
fig, ax = plt.subplots()
summer = ax.bar(index, df["student_scores"], bar_width, label="Student scores")
winter = ax.bar(index+bar_width, df["max_score"], bar_width, label="Max Scores")
ax.set_xlabel('Course')
ax.set_ylabel('Score')
ax.set_title('Current student vs Max score')
ax.set_xticks(index + bar_width / 2)
ax.set_xticklabels(["Math", "Chem", "Physics"])
ax.legend()
plt.show()
请注意,两个分数列表中的顺序应该相同。