如何使用 returns 绘图的函数创建 3D 绘图?

How do I create a 3D plot using a function that returns a plot?

我想使用一个函数制作 3D 图,该函数 return 是一个绘图和它需要的输入参数。 这是我的函数代码:

def cumulative(moment):
    bins = np.zeros(32)
    x = upper_bin
    for i in range(32):
        bins[i] = burst_average[moment, 0:i+1].sum()
    plt.ylim(ymax = 1000)
    plt.xlabel('grain size (um)')
    plt.ylabel('concentration (uL/L)')
    plt.title('grain size distribution over time')
    plt.plot(x, bins, c = 'b', label=dates[i])
    return 

import ipywidgets as widgets
from ipywidgets import interact

interact(cumulative, moment=widgets.FloatSlider(min = int(0), max = int(nr_burst-1), step = 1, description = 'moment'));

其中 x 是一个包含 32 个值的列表,bins 是一个包含 32 个值的数组,每个 moment 都会发生变化。总共制作了 nr_burst 个地块,大约是 2017 年。 该小部件有效,但我想将其包含在我的报告中,所以我想要一个 3D 图。

我试过

from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits import mplot3d    

b0 = np.linspace(0, nr_burst-1, nr_burst)
b= []
for i in range(len(b0)):
    b.append(int(b0[i]))

ax.scatter3D(cumulative(b), b)

这没有用,给出了错误 ValueError: Arguments 'xs' and 'ys' must be of same size.

我也试过 return xbplot 的功能,比如

ax.scatter3D(cumulative(b)[0], b, cumulative(b)[1])

哪个报错TypeError: 'NoneType' object is not subscriptable.

绘制原始数据后使用:

ax = plt.gca() # get the axis handle of the current graphic artist

data_2d = ax.lines[0] # this just extracts the first dataset

x,y = data_2d.get_xdata(), data_2d.get_ydata() #this will be your x and y data

使用您的原始代码,可以像这样插入:

ax.scatter3D(x, b, y)

第二个选项

将您的原始函数修改为 return 轴句柄。

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

def cumulative(moment):
    fig, ax = plt.subplots()
    bins = np.cumsum(np.arange(moment))
    x = np.arange(moment)
    ax.plot(x, bins, c = 'b')
    ax.set_xlabel('grain size (um)')
    ax.set_ylabel('concentration (uL/L)')
    ax.set_title('grain size distribution over time')
    ax.set_ylim(ymax = bins.max())
    return fig, ax

b = 32 #just a random scalar to test

fig, ax = cumulative(b) #call the function and assign the returning values

data_2d = ax.lines[0] # get your data
x,y = data_2d.get_xdata(), data_2d.get_ydata() #your data separated for x and y

plot3d = plt.figure()
ax3d = plot3d.add_subplot(111, projection='3d')
ax3d.scatter(x,b,y)