python - 如何使用返回绘图的函数创建 3D 绘图?

标签 python function plot 3d scatter

我想使用一个函数来制作 3D 绘图,该函数返回一个绘图及其需要的输入参数。 这是我的函数代码:

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 个值的数组,并且每个 时刻 都会发生变化。总共制作了nr_burst地 block ,大约是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.

我还尝试了函数返回 xb 以及 plot 之类的

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)

第二个选项

修改您的原始函数以返回轴句柄。

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)

关于python - 如何使用返回绘图的函数创建 3D 绘图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50696080/

相关文章:

python - 如何在Python循环时从列表中排除对象

python - 如何找出给定的内置 tensorflow 函数接受哪些 dtype 张量?

c++ - 函数调用作为数组元素

plot - gnuplot - 平滑插值 x=f(y)

matplotlib - 如何在 plotly 上绘制带注释的热图?

python - Flask 中间件类引发异常未捕获

python - 在 Pygame 中组合纹理图 block 、墙壁和导出的单独关卡贴图

c - 这是什么意思?返回函数()

python - 我正在更改一个变量,但是如何在函数结束时返回它的原始状态?

r - 使用 ggplot2 在 R 中绘制具有 y 轴深度(或高程)的垂直剖面的问题