Python matplotlib wireframe distortion - python

I am trying to create a plot composed of multiple wireframe spheres using matplotlib. I found a code fragment to plot one such sphere here so I thought it would be easy to extend it to multiple spheres by just calling plot_wireframe multiple times. I was wrong. Here's a code fragment:
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]
x=np.cos(u)*np.sin(v)
y=np.sin(u)*np.sin(v)
z=np.cos(v)
fig = plt.figure(figsize=(8,6))
ax = fig.gca(projection='3d')
ax.plot_wireframe(x*3.+5., y*3., z*3.,linewidths=.2)
ax.view_init(azim=30,elev=40)
ax.set_aspect("equal")
plt.show()
fig = plt.figure(figsize=(8,6))
ax = fig.gca(projection='3d')
ax.plot_wireframe(x*3.+5., y*3., z*3.,linewidths=.2)
spheres = [ [0,0,0,1], [3,0,0,1.6] ]
for v in spheres:
ax.plot_wireframe(x*v[3]+v[0], y*v[3]+v[1], z*v[3]+v[2],linewidths=.2)
ax.view_init(azim=30,elev=40)
ax.set_aspect("equal")
plt.show()
If you run that code, the first plot will show a nice sphere, while in the second all the spheres are distorted and shifted. I searched to make sure plot_wireframe can be called multiple time on the same axis but couldn't find anything. Also, I'm a Python noob, but I don't think I'm doing anything wrong.
Thank you for the help!

Short answer: adjust the axes limits manually:
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]
x=np.cos(u)*np.sin(v)
y=np.sin(u)*np.sin(v)
z=np.cos(v)
# I'm not sure what was this for.
'''
fig = plt.figure(figsize=(8,6))
ax = fig.gca(projection='3d')
ax.plot_wireframe(x*3.+5., y*3., z*3.,linewidths=.2)
ax.view_init(azim=30,elev=40)
ax.set_aspect("equal")
plt.show()
'''
fig = plt.figure(figsize=(8,6))
ax = fig.gca(projection='3d')
ax.plot_wireframe(x*3.+5., y*3., z*3.,linewidths=.2)
spheres = [ [0,0,0,1], [3,0,0,1.6] ]
for v in spheres:
ax.plot_wireframe(x*v[3]+v[0], y*v[3]+v[1], z*v[3]+v[2],linewidths=.2)
ax.view_init(azim=30,elev=40)
ax.set_xlim([0,7]) # Like so.
ax.set_ylim([-3,3])
ax.set_zlim([-3,3])
ax.set_aspect("equal")
plt.show()

Related

Bothering frame on matplotlib 3D plots

I make 3d plots with matplotlib and I always get a weird frame with a normalized scale around my plot. Where does it come from and how can I get rid of it ?
Here is an example code that drives me to the problem :
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
x = np.linspace(0,10)
y = np.linspace(0,10)
z = np.linspace(0,10)
# ------------- Figure ---------------
fig, ax = plt.subplots(figsize = (9,6))
ax = fig.gca(projection='3d')
ax.plot(np.sin(x), np.cos(y), z)
plt.show()
And here is the result :
I use plt.subplots() because I want a figure with a 3D and a 2D plot side by side.
You call plt.subplots(...) and this, of course, instantiates an Axes, complete of horizontal and vertical spines, before Matplotlib is informed that you want a 3D enabled Axes.
When you later call plt.gca(...) it's too late…
Simply use
fig, ax = plt.subplots(figsize = (9,6), subplot_kw={"projection" : "3d"})
or
fig = plt.figure(figsize = (9,6))
ax = fig.add_subplot(111, projection='3d')
Addressing OP's comment
Figure.add_subplot is pretty flexible…
fig = plt.figure()
fig.add_subplot(1,5,(1,4), projection='3d')
fig.add_subplot(1,5,5)
fig.tight_layout()
plt.show()

How to get octants in matplotlib 3D?

My code is:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
After plotting some points, when I use the plt.show() method then it displays a 3D axes system but there is only one octant. I need all 8 of them for my project. Is there any way to get them?
Thanks in advance.
It should put your data (presumably negative) in view when you plot it. However, it's worth knowing how to manually set the limits as well:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.set_xlim(-1,1)
ax.set_ylim(-1,1)
ax.set_zlim(-1,1)

Superimpose independent plots in python

I want to work with only one figure, with multiples, different and modifiable plots, whithout the subplots formalism.
Is there a way to superimpose two differents plots, in the same way as text boxes, i.e anywhere on the figure ?
Here a "gimp made" example :
Thanks !
You can use figure.add_axes to place an axes at an arbitrary location.
fig = plt.figure()
fig.add_axes([0.1,0.2,0.3,0.4])
places an axes at x=0.1, y=0.2, width=0.3, height=0.4 in figure coordinates.
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_axes([0.4,0.1,0.5,0.6], projection='3d')
X, Y = np.meshgrid(np.arange(-5, 5, 0.25), np.arange(-5, 5, 0.25))
Z = np.sin(np.sqrt(X**2 + Y**2))
surf = ax.plot_surface(X, Y, Z, cmap="plasma")
ax = fig.add_axes([0.3,0.4,0.3,.4])
plt.plot([1,2,3])
plt.show()

Updating a pyplot 3d scatter plot in a loop, grid lines overlap points

I am updating a 3d scatter plot with every iteration of a loop. When the plot is redrawn, the gridlines "go through" or "cover" the points, which makes my data more difficult to visualize. If I build a single 3d plot (no loop updating) this does not happen. The code below demonstrates the simplest case:
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import time
X = np.random.rand(100, 3)*10
Y = np.random.rand(100, 3)*5
plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X[:, 0], X[:, 1], X[:, 2])
plt.draw()
for i in range(0, 20):
time.sleep(3) #make changes more apparent/easy to see
Y = np.random.rand(100, 3)*5
ax.cla()
ax.scatter(Y[:, 0], Y[:, 1], Y[:, 2])
plt.draw()
Has anyone else encountered this problem?
It looks like MaxNoe is right in the sense that the problem is in the ax.cla()or plt.cla() call. In fact it seems it is something like a known issue.
Then there is a problem, since the clear axes method doesn't work in 3D plots and for 3D scatters there is no clean way to change the coordinates of the data points (a la sc.set_data(new_values)), as discussed in this mail list (I didn't find anything more recent).
In the mail list, however, Ben Roon points to a workaround that might be useful for you, too.
Workaround:
You need to set the new coordinates of the datapoints in the internal _ofsets3d variable of the Line3DCollectionobject returned by the scatter function.
Your example adapted would look like:
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import time
X = np.random.rand(100, 3)*10
Y = np.random.rand(100, 3)*5
plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
sc = ax.scatter(X[:, 0], X[:, 1], X[:, 2])
fig.show()
for i in range(0, 20):
plt.pause(1)
Y = np.random.rand(100, 3)*5
sc._offsets3d = (Y[:,0], Y[:,1], Y[:,2])
plt.draw()
I could narrow it down to the use of cla():
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x, y = np.meshgrid(np.linspace(-2,2), np.linspace(-2,2))
ax.plot_surface(x,y, x**2+y**2)
fig.savefig("fig_a.png")
ax.cla()
ax.plot_surface(x,y, x**2+y**2)
fig.savefig("fig_b.png")
these are the resulting plots:
This is but a workaround, as it does not resolve the issue with ax.cla() pointed out by MaxNoe. It is also not particularly pretty since it clears the entire figure, however it does the desired task:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig1 = plt.figure()
ax1 = fig1.add_subplot(111, projection='3d')
x, y = np.meshgrid(np.linspace(-2,2), np.linspace(-2,2))
ax1.plot_surface(x,y, x**2+y**2)
fig1.savefig("fig_a.png")
fig1.clf()
ax1 = fig1.add_subplot(111, projection='3d')
ax1.plot_surface(x,y, x**2+y**2)
fig1.savefig("fig_b.png")
I'd suggest using ax = fig.gca(projection='3d') instead of ax = fig.add_subplot(111, projection='3d') .

Python : How to plot 3d graphs using Python?

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.
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).
Mayavi, in particular the mlab module, provides powerful 3D plotting that will work on large and or complex data, and should be easy to use on numpy arrays.
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()
According to the documentation you want to use the ax.plot_surface(x,y,z) method. More information and chart types here.
The following should work:
x = [1,2,3]
y = [4,5,6]
z = [7,8,9]
data = zip(x,y,z)
#map data on the plane
X, Y = numpy.meshgrid(arange(0, max(x), 1), arange(0, max(y), 1))
Z = numpy.zeros((len(Y), len(X)), 'Float32')
for x_,y_,z_ in data:
Z[x_, y_] = z_ #this should work, but only because x and y are integers
#and arange was done with a step of 1, starting from 0
fig = p.figure()
ax = p3.Axes3D(fig)
ax.plot_surface(X, Y, Z)

Categories

Resources