Какой самый простой способ добавить легенду к моим подсюжетам? - PullRequest
1 голос
/ 15 апреля 2020

Я очень новичок на этом сайте. Я написал некоторый код в python, чтобы построить несколько векторов и собственных векторов на одном подплощадке и их точечное произведение с матрицей на другом подпотеке. Чтобы закончить sh off, я хотел бы добавить легенду с цветом каждого вектора / собственного вектора, как на графиках.

Вот мой код:

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

Это генерирует два сюжета, как показано на этом изображении.

Subplots

Извините, если я отформатировал что-то не так в этом посте, пожалуйста, не добавляйте меня.

Ответы [ 2 ]

0 голосов
/ 15 апреля 2020

Вы нашли его сами, но я дам вам версию, которую я делал с меньшим количеством звонков, если это поможет :):

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

output

0 голосов
/ 15 апреля 2020

Как это:

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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...