Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot 2d math vectors with matplotlib?

Tags:

How can we plot 2D math vectors with matplotlib? Does anyone have an example or suggestion about that?

I have a couple of vectors stored as 2D numpy arrays, and I would like to plot them as directed edges.

The vectors to be plotted are constructed as below:

import numpy as np # a list contains 3 vectors; # each list is constructed as the tail and the head of the vector a = np.array([[0, 0, 3, 2], [0, 0, 1, 1], [0, 0, 9, 9]])  

Edit:

I just added the plot of the final answer of tcaswell for anyone interested in the output and want to plot 2d vectors with matplotlib: enter image description here

like image 540
pacodelumberg Avatar asked Sep 04 '12 14:09

pacodelumberg


People also ask

How do you plot two vectors in Python?

MatPlotLib with PythonCreate a matrix of 2×3 dimension. Create an origin point, from where vecors could be originated. Plot a 3D fields of arrows using quiver() method with origin, data, colors and scale=15.

How do I plot a vector in NumPy?

We need to start by initializing the coordinates of the vectors and the origin point of the graph. For this, we will use a numpy array. We will then use the pyplot. quiver() function to create a plot using these coordinates.


1 Answers

The suggestion in the comments by halex is correct, you want to use quiver (doc), but you need to tweak the properties a bit.

import numpy as np import matplotlib.pyplot as plt  soa = np.array([[0, 0, 3, 2], [0, 0, 1, 1], [0, 0, 9, 9]]) X, Y, U, V = zip(*soa) plt.figure() ax = plt.gca() ax.quiver(X, Y, U, V, angles='xy', scale_units='xy', scale=1) ax.set_xlim([-1, 10]) ax.set_ylim([-1, 10]) plt.draw() plt.show() 
like image 180
tacaswell Avatar answered Sep 29 '22 12:09

tacaswell