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

时间:2018-06-05 08:56:29

标签: 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个值的数组,每个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.

我还尝试使用该函数返回xb以及plot

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

其中包含错误TypeError: 'NoneType' object is not subscriptable.

1 个答案:

答案 0 :(得分:0)

绘制原始数据后使用:

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)