【问题标题】:How to plot the average of a column in a NxM matrix , python如何绘制 NxM 矩阵中列的平均值,python
【发布时间】:2021-06-19 11:59:11
【问题描述】:

大家好,我有一个任务,我应该创建两个图,其中输入是一个名为 Grades 的变量,它是一个 N×M 矩阵,包含给 N 个学生的 7 步等级的成绩 在 M 个不同的任务上。

第一个图是我通过创建 for 循环成功绘制的条形图。 第二个图必须将每个作业的平均成绩显示为一条线。

这是我尝试过的,但请注意我已经给出了变量等级值来测试绘图是否有效:

import numpy as np
import matplotlib.pyplot as plt


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



fig2=plt.figure()
y=''
x=''

for i in range(len(grades)):
    y=np.array([np.mean(grades[:,i],axis=0)])
    x=np.array([i+1])

    plt.plot(x,y,'-',label=f'Average of assignment {i+1}')
   
#when taking the length of a matrix by calling the rows you get the amount of columns

plt.xlabel('Assignments')
plt.ylabel('Grades')
    
plt.title('The distribution of grades per assignment') 
    
    
#putting legends next to the graph.
plt.legend(loc='center left',prop={"size":10},bbox_to_anchor=(1, 0.5))
    
#displaying the plot.
plt.savefig('Gradesperassignment',bbox_inches='tight')

【问题讨论】:

    标签: python python-3.x matplotlib


    【解决方案1】:
    import numpy as np
    import matplotlib.pyplot as plt
    
    grades=np.array([[12,10,7,4,2,-3,4,7,10,12],[2,0,-3,10,4,7,2,0,-3,10],[-3,0,2,4,7,12,12,4,7,2]])
    len(grades)
    fig2=plt.figure()
    y=''
    x=''
    X=[]
    Y=[]
    for i in range(len(grades)):
        y=np.array([np.mean(grades[:,i],axis=0)])
        x=np.array([i+1])
        print(x,y)
        X.append(x)
        Y.append(y)
    plt.plot(X,Y)
    #when taking the lentgh of a matrix by calling the rows you get the amount of columns
    plt.xlabel('Assignments')
    plt.ylabel('Grades') 
    plt.title('The distribution of grades per assignment')   
    #putting legends next to the graph.
    plt.legend(loc='center left',prop={"size":10},bbox_to_anchor=(1, 0.5)) 
    #displaying the plot.
    #plt.savefig('Gradesperassignment',bbox_inches='tight')
    plt.show()
    

    在里面为你计算一对 x,y 并绘制它。但为了画一条线,它至少需要 2 个点。在 X 列表中添加所有 x,在 Y 列表中添加 y,然后绘制 X,Y

    【讨论】:

    • 大家好,如果矩阵中有负值​​,代码将无法工作?它说:Indexerror: index 3 is out of bounds for axis 1 with size 3
    • 您尝试的值是什么?在哪个命令中出现错误?
    • 我已经上传了整个脚本作为下面的答案
    • Indexerror: index 3 is out of bounds for axis 1 with size 3 表示您有一个包含 3 列 0、1、2 的数组,并且您询问第 3 列。问题出在。 for i in range(len(grades)): len(grades) 为您提供数组的行,对于您需要的列 for i in range(len(grades[0])):
    • 在 for a,row in enumerate(grades) 之后:您必须使用我们用于其他绘图的 X,Y 之类的列表才能绘制 for 之外的值
    【解决方案2】:

    这里@virxen:

    import numpy as np
    import matplotlib.pyplot as plt
    
    from FinalGradeFunction import computeFinalGrades
    from loaddatafunction import dataLoad
    
    data=dataLoad('data.csv')
    df1= data.drop(['StudentID', 'Name'], axis=1)
                 
    grades=df1.to_numpy()
    grades is in this case=array([[ 7,  7,  4],
           [12, 10, 10],
           [-3,  7,  2],
           [10, 12, 12],
           [ 7,  7,  5],
           [12, 10, 10],
           [-3,  7,  2],
           [10, 12, 12]], dtype=int64)
    
    def gradesPlot(grades):
        # gradesPlot is a function which generates two plots.
        #one which is a bar plot and the other is a graph.
        # Usage: gradesPlot(grades)
        #
        # Input:the grades of the students given as an NxM matrix 
        # containing the grades on the 7-step-scale given to N students on M different assignments
        # Output grades (two plots).
        #
        # Authors: Yaren Kart, 2021.
    
        
        #Plot1 Find Grades
        
        #Counting the occurrences of the grades from the 7-step-scale:
        #creating a vector made up of the number of zeros equivalent to the length of the Final_Grades.
        Final_Grades=computeFinalGrades(grades)
        
        v=np.zeros(len(Final_Grades))
     
        #counting how many times the different grades occur and putting the values in the vector v. 
        for i in range(len(v)):
            v[i]=sum(Final_Grades==i+1)
            
        #Ploting the bar plot:
        #ploting the figure.
        fig1 = plt.figure()  
        
        #determining the space between the bars.
        ax = fig1.add_axes([0,0,1.5,1.5]) 
        
        #setting the 7-step-scale.
        x = ['-3', '00', '02', '4','7','10','12'] 
        
        #creating the bar plot.
        ax.bar(x,v) 
        
        #labelling the x-axis.
        plt.xlabel('The 7-step-scale grades') 
        
        # labeling the y-axis.
        plt.ylabel('The number of students')
        
        #giving the bar plot a title.
        plt.title('The distribution of final grades') 
        
        plt.savefig('Finalgrades',bbox_inches='tight')
            
    
        
    #-----------------------------------------------------------------------------------------------------------------------------------------------    
        #Plot2 "grades per assignment"
       
        fig2=plt.figure()
        
        #will move the x- and y-values so that the dots wont overlap
        jitter_min = -0.1
        jitter_max = 0.1
    
    
        #creating a for loop
        #iterate over the grades array, one row at a time. 
        #enumerate returns an index - a, and the row.
        for a,row in enumerate(grades):
            
            x = (a*np.ones(len(row)) + (jitter_max-jitter_min)*np.random.random(size=len(row))+jitter_min)
            plt.plot(x, row, 'o', label='Assignment {:1d}'.format(a), clip_on=False)
    
        plt.xlabel('Assignments')
        plt.ylabel('Grades')
            
        plt.title('The distribution of grades per assignment) 
        
        
        #putting legends next to the graph.
        plt.legend(loc='center left',prop={"size":10},bbox_to_anchor=(1, 0.5))
       
        y=''
        x=''
        X=[]
        Y=[]
    
        #Creating a for loop
        for i in range(len(grades)):
            y=np.array([np.mean(grades[:,i],axis=0)])
            x=np.array([i+1])
            
            #Adding all the x values into X and all the y-values into Y.
            X.append(x)
            Y.append(y)
        
        plt.plot(X,Y,label='The average of the assignments.')
        
        #assigning labels and a title to the graph.
        plt.xlabel('Assignments')
        plt.ylabel('Grades') 
        plt.title('The distribution of grades per assignment')   
       
        #putting legends next to the graph.
        plt.legend(loc='center left',prop={"size":10},bbox_to_anchor=(1, 0.5)) 
       
        #plt.savefig('Gradesperassignment',bbox_inches='tight')
     
        plt.savefig('Gradesperassignment',bbox_inches='tight')    
        
    
    print(gradesPlot(grades))
       
       
       
       
       
       
       
       
       
       
       
       
       
    
    
        
       
       
       
       
       
       
       
       
       
       
       
       
       
    

    【讨论】:

    • 它应该打印两个图,以前可以,但现在不行,我真的不明白
    【解决方案3】:
    import numpy as np
    import matplotlib.pyplot as plt
    
    grades=np.array([[ 7,  7,  4],
           [12, 10, 10],
           [-3,  7,  2],
           [10, 12, 12],
           [ 7,  7,  5],
           [12, 10, 10],
           [-3,  7,  2],
           [10, 12, 12]], dtype='int64')
    
    def gradesPlot(grades):  
        #Plot1 Find Grades
        Final_Grades=np.array([7,10,7,12,7,2,12])
        v=np.zeros(len(Final_Grades))
        fig1 = plt.figure() 
        ax = fig1.add_axes([0,0,1.5,1.5]) 
        x = ['-3', '00', '02', '4','7','10','12']
        for i in range(len(v)):
            v[i]=sum(Final_Grades==i+1)
        ax.bar(x,v) 
        plt.xlabel('The 7-step-scale grades') 
        plt.ylabel('The number of students')
        plt.title('The distribution of final grades') 
        plt.savefig('Finalgrades',bbox_inches='tight')
    #-----------------------------------------------------------------------------------------------------------------------------------------------    
        #Plot2 "grades per assignment"
        fig2=plt.figure()
        jitter_min = -0.1
        jitter_max = 0.1
        XX=[]
        YY=[]
        for a,row in enumerate(grades):
            x = (a*np.ones(len(row)) + (jitter_max-jitter_min)*np.random.random(size=len(row))+jitter_min)
            XX.append(x)
            YY.append(row)
        plt.plot(XX, YY, 'o', label='Assignment {:1d}'.format(a), clip_on=False)#
        plt.xlabel('Assignments')
        plt.ylabel('Grades')
        plt.title('The distribution of grades per assignment')
        plt.legend(loc='center left',prop={"size":10},bbox_to_anchor=(1, 0.5))
        y=''
        x=''
        X=[]
        Y=[]
        for i in range(len(grades[0])):
            y=np.array([np.mean(grades[:,i],axis=0)])
            x=np.array([i+1])
            X.append(x)
            Y.append(y)
        plt.plot(X,Y,label='The average of the assignments.')#
        plt.xlabel('Assignments')
        plt.ylabel('Grades') 
        plt.title('The distribution of grades per assignment')   
        plt.legend(loc='center left',prop={"size":10},bbox_to_anchor=(1, 0.5)) 
        plt.savefig('Gradesperassignment',bbox_inches='tight')    
        plt.show()
    print(gradesPlot(grades))
    

    这对你有用吗?

    【讨论】:

    • 不幸的是,它没有。即使只有三个作业,它也绘制了七个
    • 但是我已经编写了一个新代码并且可以正常工作,非常感谢您的帮助
    猜你喜欢
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 2018-09-23
    • 1970-01-01
    • 2018-12-02
    • 2013-01-04
    • 2014-01-21
    相关资源
    最近更新 更多