• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Pruebas Online
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

473
Vistas
Cómo trazar vectores en python usando matplotlib

Estoy tomando un curso de álgebra lineal y quiero visualizar los vectores en acción, como la suma de vectores, el vector normal, etc.

Por ejemplo:

 V = np.array([[1,1],[-2,2],[4,-7]])

En este caso, quiero trazar 3 vectores V1 = (1,1), M2 = (-2,2), M3 = (4,-7) .

Entonces debería poder agregar V1, V2 para trazar un nuevo vector V12 (todos juntos en una figura).

cuando uso el siguiente código, la trama no es la esperada

 import numpy as np import matplotlib.pyplot as plt M = np.array([[1,1],[-2,2],[4,-7]]) print("vector:1") print(M[0,:]) # print("vector:2") # print(M[1,:]) rows,cols = MTshape print(cols) for i,l in enumerate(range(0,cols)): print("Iteration: {}-{}".format(i,l)) print("vector:{}".format(i)) print(M[i,:]) v1 = [0,0],[M[i,0],M[i,1]] # v1 = [M[i,0]],[M[i,1]] print(v1) plt.figure(i) plt.plot(v1) plt.show()
almost 3 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

¿Qué tal algo como

 import numpy as np import matplotlib.pyplot as plt V = np.array([[1,1], [-2,2], [4,-7]]) origin = np.array([[0, 0, 0],[0, 0, 0]]) # origin point plt.quiver(*origin, V[:,0], V[:,1], color=['r','b','g'], scale=21) plt.show()

ingrese la descripción de la imagen aquí

Luego, para sumar dos vectores cualesquiera y trazarlos en la misma figura, hágalo antes de llamar a plt.show() . Algo como:

 plt.quiver(*origin, V[:,0], V[:,1], color=['r','b','g'], scale=21) v12 = V[0] + V[1] # adding up the 1st (red) and 2nd (blue) vectors plt.quiver(*origin, v12[0], v12[1]) plt.show()

ingrese la descripción de la imagen aquí

NOTA: en Python2 use origin[0], origin[1] en lugar de *origin

almost 3 years ago · Santiago Trujillo Denunciar

0

Esto también se puede lograr usandomatplotlib.pyplot.quiver , como se indica en la respuesta vinculada;

 plt.quiver([0, 0, 0], [0, 0, 0], [1, -2, 4], [1, 2, -7], angles='xy', scale_units='xy', scale=1) plt.xlim(-10, 10) plt.ylim(-10, 10) plt.show()

salida mpl

almost 3 years ago · Santiago Trujillo Denunciar

0

Su principal problema es que crea nuevas figuras en su bucle, por lo que cada vector se dibuja en una figura diferente. Esto es lo que se me ocurrió, avísame si aún no es lo que esperas:

CÓDIGO:

 import numpy as np import matplotlib.pyplot as plt M = np.array([[1,1],[-2,2],[4,-7]]) rows,cols = MTshape #Get absolute maxes for axis ranges to center origin #This is optional maxes = 1.1*np.amax(abs(M), axis = 0) for i,l in enumerate(range(0,cols)): xs = [0,M[i,0]] ys = [0,M[i,1]] plt.plot(xs,ys) plt.plot(0,0,'ok') #<-- plot a black point at the origin plt.axis('equal') #<-- set the axes to the same scale plt.xlim([-maxes[0],maxes[0]]) #<-- set the x axis limits plt.ylim([-maxes[1],maxes[1]]) #<-- set the y axis limits plt.legend(['V'+str(i+1) for i in range(cols)]) #<-- give a legend plt.grid(b=True, which='major') #<-- plot grid lines plt.show()

PRODUCCIÓN:

ingrese la descripción de la imagen aquí

EDITAR CÓDIGO:

 import numpy as np import matplotlib.pyplot as plt M = np.array([[1,1],[-2,2],[4,-7]]) rows,cols = MTshape #Get absolute maxes for axis ranges to center origin #This is optional maxes = 1.1*np.amax(abs(M), axis = 0) colors = ['b','r','k'] for i,l in enumerate(range(0,cols)): plt.axes().arrow(0,0,M[i,0],M[i,1],head_width=0.05,head_length=0.1,color = colors[i]) plt.plot(0,0,'ok') #<-- plot a black point at the origin plt.axis('equal') #<-- set the axes to the same scale plt.xlim([-maxes[0],maxes[0]]) #<-- set the x axis limits plt.ylim([-maxes[1],maxes[1]]) #<-- set the y axis limits plt.grid(b=True, which='major') #<-- plot grid lines plt.show()

EDITAR SALIDA: ingrese la descripción de la imagen aquí

almost 3 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda