【问题标题】:Creating a bar graph for data comparison in python在python中创建用于数据比较的条形图
【发布时间】:2020-10-08 02:21:01
【问题描述】:

对于一个项目,我编写了一个代码,学生可以在其中输入他的姓名、录取编号、数学、物理和化学分数。现在我想要一个条形图来比较他的得分和最高得分者。我已经定义了一个列表(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()

但我不知道如何修改此代码以满足我的需要...

任何帮助将不胜感激!

【问题讨论】:

    标签: python


    【解决方案1】:

    只需修改您发布的代码,就可以解决问题:

    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()
    

    请注意两个分数列表中的顺序应该相同。

    【讨论】:

      猜你喜欢
      • 2019-04-10
      • 2018-08-19
      • 2016-07-06
      • 2023-03-26
      • 2011-12-13
      • 2021-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多