python - 根据作业编号绘制成绩

标签 python python-3.x matplotlib

我想用 Python3 画一个图,在 x 轴上显示作业,在 y 轴上显示成绩。 x 轴必须显示从 1 到 M 的所有作业,y 轴必须显示 3 到 12 的所有成绩。

输入是 M 项作业的成绩矩阵:例如对于 6 项作业,我有以下输入:

array([[10, -3, 10, ..., 7, 0, 12],
   [12, 12, 12, ..., 10, 0, 12],
   [7, 7, 10, ..., 10, 0, 10],
   [7, 4, 7, ..., 7, 0, 12],
   [-3, 4, 7, ..., 4, 4, 12],
   [7, 4, 4, ..., 4, 0, 12]], dtype=object)
  • 第一行 - 作业 1 成绩
  • 第二行 - 作业 2 个成绩
  • 等等

绘图还必须包含:

  1. 每个给定的成绩都用点标记。我需要添加一个小的随机数 每个点的 x 和 y 坐标的数字(-0.1 和 0.1 之间), 能够区分不同的点,否则这些点将位于每个点的顶部 其他当超过一名学生在同一类(class)中获得相同成绩时 作业。
  2. 每项作业的平均成绩绘制为一条线。

我开始尝试使用 for 循环来绘制每个作业,但它似乎不起作用 - 因此我现在陷入困境。

import matplotlib.pyplot as plt
yaxis = np.arange(-3, 13)    
for i in range(len(assignments)-1):
    plt.plot(assignments[i, :], yaxis, label = "Assignemnt [i]")

plt.title("Grades per assignment")
plt.xlabel("Assignments")
plt.ylabel("Grades")
plt.show()  

最佳答案

如果我理解你的问题,这就是你想要的吗? 不确定您希望如何表示平均成绩,但我将其作为练习留给您。

编辑

对于每次调用plot(),您都必须有一个维度相同的x 数组和y 数组。在这里,我使用 enumerate() 一次一行地迭代数据数组,它返回一个索引(我将其称为 a),以及行(我将其称为 a) 成绩。有 6 行,因此 a 将依次取值 0、1、2、3、4 和 5。

然后,由于您想要根据作业编号 a 绘制每个成绩,因此您可能会尝试 plot(a,grades)。但是,由于 xy 需要具有相同的维度,因此我们需要生成一个与 grades 具有相同维度的数组,即x = a*np.ones(len(grades)) 的作用。从那里,您可以执行plot(x,grades)。但是,正如您在问题中指出的那样,同等成绩会​​重叠。

为了避免重叠,我使用公式 (jitter_max-jitter_min)*np.random.random(size=len(grades) 在 [-0.1, 0.1) 之间添加了一个随机数))+jitter_min (see the documentation for np.random.random())。

要绘制平均值,您只需逐行计算平均值,将该值存储在数组中,然后针对包含分配编号(0,1,2,3 ,...)。要将其绘制为一条线,而不是简单的点, check outthe documentation for plot : plot(..., ..., 'o-')

data = np.array([[10, -3, 10, 7, 0, 12],
   [12, 12, 12, 10, 0, 12],
   [7, 7, 10, 10, 0, 10],
   [7, 4, 7, 7, 0, 12],
   [-3, 4, 7, 4, 4, 12],
   [7, 4, 4, 4, 0, 12]])

jitter_min = -0.1
jitter_max = 0.1
for a,grades in enumerate(data):
    x = a*np.ones(len(grades)) + (jitter_max-jitter_min)*np.random.random(size=len(grades))+jitter_min
    plt.plot(x, grades, 'o', label='Assignment #{:d}'.format(a), clip_on=False)
plt.xlabel('Assignments')
plt.ylabel('Grades')

enter image description here

关于python - 根据作业编号绘制成绩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40764723/

相关文章:

Python - 两个相同长度的列表之间的完全区别

python - 从具有多个数据集的散点图中获取 x,y?

python - socket.recvmsg 忽略 ancbufsize、辅助数据

python - 为什么空闲 Python 线程消耗高达 90% 的 CPU?

python - 在 Python 中一致地格式化数字

python - Python 中的配置类

javascript - 尝试将用户定向到新的 HTML 页面时出现问题 Python Bottle

python - 类型错误: 'in <string>' 需要字符串作为左操作数,而不是列表(列表理解)

python - Matplotlib 向条形图添加了太多标签

python - 如何在matplotlib中使主轴透明,同时使zoomed_inset_axes不透明