הוד רז
הוד רז

Reputation: 21

using quiver in python to plot a 3d vector

Super simple question, I know, but it's my first day using python and have to learn to use it quickly. I'd like to use quiver(it has to be quiver) to draw 3D vector. to make it simple, if I want to draw the vector (1,1,1) and see it like in the following picture(in the right directions of course), how can I do it? this is what I've been trying to do:

import matplotlib.pyplot as plt
plt.quiver(0, 0, 0, 1, 1, 1, scale=1, color='g')

enter image description here

Upvotes: 2

Views: 19680

Answers (2)

Mohit Lamba
Mohit Lamba

Reputation: 1373

The above answer in throws an error especially in the latest version of python. More precisely the problematic line is ax = fig.gca(projection='3d')

One can use the below code which runs seamlessly

import matplotlib.pyplot as plt #for creating plot
import numpy as np  #for numerical operations
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.quiver(0,0,0,1.2,1.4,1.8, length=1)
ax.set_xlim([0, 2])
ax.set_ylim([0, 2])
ax.set_zlim([0, 2])
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()

An the output is as below,

enter image description here

Upvotes: 0

Tetra
Tetra

Reputation: 163

plt.quiver only works for 1D and 2D arrays. You should use mplot3d to show your figure in 3 dimensions:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_xlim3d(0, 0.8)
ax.set_ylim3d(0, 0.8)
ax.set_zlim3d(0, 0.8)
ax.quiver(0, 0, 0, 1, 1, 1, length = 0.5, normalize = True)
plt.show()

I recommend you read the documentation on pyplot.quiver and axes3d.quiver.

Upvotes: 3

Related Questions