Updating A 3d Python Plot During A Convergence Iteration
I try to create a plotting script that plots my data in two 3d structures (with one variable as a color) that I use in a loop in which the data is supposed to converge. I would lik
Solution 1:
Two ways you could do this would be
- Use a combination of
set_offsets()
andset_3d_properties
- Clear the
figure
and/oraxes
object(s) and plot a newscatter
every iteration
Example using set_offsets()
and set_3d_properties
:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
x = np.linspace(0, np.pi*2, 25)
y = np.sin(x)
z = np.cos(x)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
defplot(ax):
return ax.scatter(x, y, z)
defupdate(s):
s.set_offsets(np.stack([x, y], 1))
s.set_3d_properties(z, 'z')
s = plot(ax)
plt.savefig("./before.png")
y = np.cos(x)
z = np.sin(x)
update(s)
plt.savefig("./after.png")
Example clearing and redrawing:
defplot(fig, ax):
ax.scatter(x, y, z)
plot(fig, ax)
plt.savefig("./before.png")
y = np.cos(x)
z = np.sin(x)
plt.cla()
plot(fig, ax)
plt.savefig("./after.png")
Or, if you want to accumulate the data from every iteration in the same scatter plot, you can just append the new data points to the x
, y
, and z
objects and use one of the above methods.
Example with accumulation:
defplot(ax):
return ax.scatter(x, y, z)
defupdate(s):
s.set_offsets(np.stack([x, y], 1))
s.set_3d_properties(z, 'z')
s = plot(ax)
plt.savefig("./before.png")
x = np.vstack([x,x])
y = np.vstack([y, np.cos(x)])
z = np.vstack([z, np.sin(x)])
update(s)
plt.savefig("./after.png")
I would recommend the combination of set_offsets()
and set_3d_properties()
. See this answer for more about scoping the figure
and axes
objects.
Post a Comment for "Updating A 3d Python Plot During A Convergence Iteration"