Python : How to plot 3d graphs using Python?


Question

I am using matplotlib for doing this

from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib
import matplotlib.pyplot as plt

fig = plt.figure()
ax = Axes3D(fig)

x = [6,3,6,9,12,24]
y = [3,5,78,12,23,56]

ax.plot(x, y, zs=0, zdir='z', label='zs=0, zdir=z')

plt.show()

Now this builds a graph that is horizontal in the 3d space. How do I make the graph vertical so that it faces the user?

What I want to do is build multiple such vertical graphs that are separated by some distance and are facing the user.

1
23
2/19/2010 11:19:10 AM

Accepted Answer

bp's answer might work fine, but there's a much simpler way.

Your current graph is 'flat' on the z-axis, which is why it's horizontal. You want it to be vertical, which means that you want it to be 'flat' on the y-axis. This involves the tiniest modification to your code:

from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib
import matplotlib.pyplot as plt

fig = plt.figure()
ax = Axes3D(fig)

x = [6,3,6,9,12,24]
y = [3,5,78,12,23,56]
# put 0s on the y-axis, and put the y axis on the z-axis
ax.plot(xs=x, ys=[0]*len(x), zs=y, zdir='z', label='ys=0, zdir=z')
plt.show()

Then you can easily have multiple such graphs by using different values for the ys parameter (for example, ys=[2]*len(x) instead would put the graph slightly behind).

12
2/19/2010 8:51:33 AM

You can set the view angle of the 3d plot with the view_init() function. The example below is for version 1.1 of matplotlib.

from mpl_toolkits.mplot3d import axes3d
import numpy as np
import matplotlib
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x = [6,3,6,9,12,24]
y = [3,5,78,12,23,56]

ax.plot(x, y, zs=0, zdir='z', label='zs=0, zdir=z')
ax.view_init(90, -90)
plt.show()

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon