【问题标题】:What is the easiest way to add a legend to my subplots?向我的子图添加图例的最简单方法是什么?
【发布时间】:2020-07-28 15:02:52
【问题描述】:

我是这个网站的新手,我在 python 中编写了一些代码来在一个子图上绘制一些向量和特征向量,并在另一个子图上绘制它们与矩阵的点积。最后,我想在子图上添加一个带有每个向量/特征向量颜色的图例。

这是我的代码:

import numpy as np
import matplotlib.pyplot as plt
#The Matrix
A=np.array([[1,1.5],[0,2]]) 
#Calculating Eigenvectors of The Matrix
l,e=np.linalg.eig(A)
EVect1=e[0]
EVect2=e[1]
#Combined Array of Vectors in Question and calulated Eigenvectors
V=np.array([[1,2],[0,1],[-1,2],[-0.5,1],e[0],e[1]])

#labels for vectors
Legend_labels=(['Vector1','Vector2','Vector3','Vector4''Eigenvector1','Eigenvector2'])
#List of colours to plot vectors
c=(['r','y','m','b','g','k'])

#making the subplots
for i in range(1, 3):
        plt.subplot(1, 2, i)
        plt.xlabel('x') 
        plt.ylabel('y')
        plt.xlim(-5,5)
        plt.ylim(-5,5)
        plt.grid()

def plot_vector(v,c): 
    plt.arrow(0,0,v[0],v[1],color=c,head_width=0.2) 

#making the first sub plot                       
plt.subplot(1,2,1)
plt.title("The Four Vectors and the Eigenvectors of Matrix A", fontsize=6)
for i in range(0,6):
    plot_vector(V[i],c[i])

#making the second subplot
plt.subplot(1,2,2)
plt.title("Dot Products of Each Vector with Matrix A",fontsize=6)
for i in range(0,6):
    plot_vector((np.dot(A,V[i])),c[i])  

这会生成两个子图,如图所示。

抱歉,如果我在帖子中的格式有误,请不要给我留言。

【问题讨论】:

    标签: python numpy matplotlib spyder


    【解决方案1】:

    像这样:

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.lines import Line2D    
    #The Matrix
    A=np.array([[1,1.5],[0,2]]) 
    #Calculating Eigenvectors of The Matrix
    l,e=np.linalg.eig(A)
    EVect1=e[0]
    EVect2=e[1]
    #Combined Array of Vectors in Question and calulated Eigenvectors
    V=np.array([[1,2],[0,1],[-1,2],[-0.5,1],e[0],e[1]])
    
    #labels for vectors
    Legend_labels=(['Vector1','Vector2','Vector3','Vector4''Eigenvector1','Eigenvector2'])
    #List of colours to plot vectors
    c=(['r','y','m','b','g','k'])
    custom_lines = [Line2D([0],[0], color='r'),
                    Line2D([0],[0], color='y'),
                    Line2D([0],[0], color='m'),
                    Line2D([0],[0], color='b'),
                    Line2D([0],[0], color='g'),
                    Line2D([0],[0], color='k')]
    for i in range(1, 3):
    #making the subplots
            plt.subplot(1, 2, i)
            plt.xlabel('x') 
            plt.ylabel('y')
            plt.xlim(-5,5)
            plt.ylim(-5,5)
            plt.grid()
    
    def plot_vector(v,c): 
        plt.arrow(0,0,v[0],v[1],color=c,head_width=0.2) 
    
    #making the first sub plot                       
    plt.subplot(1,2,1)
    plt.title("The Four Vectors and the Eigenvectors of Matrix A", fontsize=6)
    for i in range(0,6):
        plot_vector(V[i],c[i])
        plt.legend(custom_lines, ['Vector1','Vector2','Vector3','Vector4','Eigenvector1','Eigenvector2'],loc=8)
    
    #making the second subplot
    plt.subplot(1,2,2)
    plt.title("Dot Products of Each Vector with Matrix A",fontsize=6)
    for i in range(0,6):
        plot_vector((np.dot(A,V[i])),c[i]) 
        plt.legend(custom_lines, ['Vector1','Vector2','Vector3','Vector4','Eigenvector1','Eigenvector2'],loc=8)
    

    【讨论】:

    • 另外你不需要调用它六次。最后一次就足够了。
    【解决方案2】:

    你自己找到了,但如果有帮助的话,我会让你使用我正在做的版本,减少调用次数:):

    #making the subplots                    
    fig, axs = plt.subplots(1, 2, figsize=(8, 4))
    
    axs[0].set_title("The Four Vectors and the Eigenvectors of Matrix A", fontsize=6)
    axs[1].set_title("Dot Products of Each Vector with Matrix A",fontsize=6)
    
    for ax in axs:
        ax.grid(zorder=-1)
        ax.set_xlim([-5,5])
        ax.set_xlabel('x') 
        ax.set_ylim([-5,5])
        ax.set_ylabel('y')
    
    def plot_vector(ax,v,c): 
        arrow = ax.arrow(0,0,v[0],v[1],color=c,head_width=0.2,zorder=2.5) 
        return arrow
    
    arrows_1 = []
    arrows_2 = []   
    for i in range(6):
        arrow1 = plot_vector(axs[0],V[i],c[i])
        arrows_1.append(arrow1)
        arrow2 = plot_vector(axs[1],(np.dot(A,V[i])),c[i]) 
        arrows_2.append(arrow2)
    
    axs[0].legend(arrows_1, Legend_labels,loc="lower right",fontsize=6)
    axs[1].legend(arrows_2, Legend_labels,loc="lower right",fontsize=6) 
    

    【讨论】:

      猜你喜欢
      • 2016-01-26
      • 2010-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-17
      • 2012-01-22
      相关资源
      最近更新 更多