在收敛迭代过程中更新3d python图

RikDevelops

我尝试创建一个绘图脚本,将我的数据绘制成两个3d结构(以一个变量作为颜色),该结构在应该收敛数据的循环中使用。我想在每次迭代时更新该图,而不是创建一个新图。关于如何实现此目标的任何想法?

功能:

import matplotlib.pyplot as plt
import numpy as np

def colorplot_3D(network, color_variable_1, color_variable_2):

    net = network

    X, Y, Z = net['pore.coords'][net.Ps].T
    X_max, Y_max, Z_max = np.amax(X), np.amax(Y), np.amax(Z)

    plt.ion()
    fig = plt.figure()
    ax = fig.add_subplot(211, projection='3d')
    plot_1 = ax.scatter(xs=X, ys=Y, zs=Z, c=color_variable_1)
    plt.xlabel('x-position')
    plt.ylabel('y-position')
    cbar_1 = fig.colorbar(plot_1)
    ax.text(X_max / 2, 0, Z_max * 1.2, 'membrane')
    ax.text(X_max / 2, Y_max, Z_max * 1.2, 'current collector')
    ax.text(-0.2 * X_max, Y_max / 2, Z_max * 1.2, 'flow inlet')
    ax.text(1.3 * X_max, Y_max / 2, Z_max * 1.2, 'flow outlet')
    cbar_1.ax.set_ylabel('pore concentration [mol/m3]')

    ax2 = fig.add_subplot(212, projection='3d')
    plot_2 = ax2.scatter(xs=X, ys=Y, zs=Z, c=color_variable_2)
    cbar_2 = fig.colorbar(plot_2)
    cbar_2.ax.set_ylabel('liquid potential [V]')
    ax2.text(X_max / 2, 0, Z_max * 1.2, 'membrane')
    ax2.text(X_max / 2, Y_max, Z_max * 1.2, 'current collector')
    ax2.text(-0.2 * X_max, Y_max / 2, Z_max * 1.2, 'flow inlet')
    ax2.text(1.3 * X_max, Y_max / 2, Z_max * 1.2, 'flow outlet')
    plt.draw()

    return fig
威廉·米勒

您可以通过两种方式做到这一点

  • 结合使用set_offsets()set_3d_properties
  • 清除figure和/或axes对象并在scatter每次迭代中绘制一个新的

使用set_offsets()和的示例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')

def plot(ax):
    return ax.scatter(x, y, z)

def update(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")

清除和重绘示例:

def plot(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")

或者,如果你想从每次迭代积聚在同一散点图中的数据,你可以追加新数据指向xy以及z上述方法的对象和用途之一。

累积示例:

def plot(ax):
    return ax.scatter(x, y, z)

def update(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")

我建议结合使用set_offsets()set_3d_properties()有关范围界定对象的更多信息,请参见此答案figureaxes

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章