Home > Mobile >  How to plot multiple graphs (loaded by a loop) into the same 3D plot?
How to plot multiple graphs (loaded by a loop) into the same 3D plot?

Time:06-08

My code loads 15 time-series data via a for loop. The time-series are then transformed into 3D phase space. I would like to plot the 15 trajectories into one 3D coordinate system (phase space), but my code creates a new 3D plot for every time-series (Data).

Here is the relevant part of my code:

for Subject in Subjects:
    Data = np.loadtxt("path/to/files...")

    Colormap = plt.get_cmap("tab20c_r")
    Segment_Colormap = Colormap(np.linspace(0, 1, len(Subjects)))

    x_list = pd.Series(Data) # pd.Series
    y_list = x_list.shift(Mean_Lag) # pd.DataFrame.shift
    z_list = x_list.shift(Mean_Lag*2)

    plt.figure().add_subplot(projection="3d")
    plt.plot(x_list, y_list, z_list, lw=0.5,
         c=Segment_Colormap[Subjects.index(Subject)])

plt.show()

I know that the issue is due to the fact that the line plt.figure().add_subplot(projection="3d") is part of my for loop.

However, when I remove the related code lines out of the loop, such as follows

    x_list = pd.Series(Data) # pd.Series
    y_list = x_list.shift(Mean_Lag) # pd.DataFrame.shift
    z_list = x_list.shift(Mean_Lag*2)

plt.figure().add_subplot(projection="3d")
plt.plot(x_list, y_list, z_list, lw=0.5,
         c=Segment_Colormap[Subjects.index(Subject)])

plt.show()

the result is that my code only plots the last time-series (Data) of the for loop. What would be the solution so that all 15 loaded files by the for loop are plotted into one and the same 3D plot? I didn't face this problem with 2D plots before, so something seems to be different for a 3D plot.

CodePudding user response:

In your first case, the issue is that you call plt.figure().add_subplot(projection="3d") inside the for loop, meaning a new figure is created with each iteration.

In your second case, the issue is that you call plt.plot(x_list, y_list, z_list, lw=0.5, c=Segment_Colormap[Subjects.index(Subject)]) outside of the for loop, meaning only the last iteration is plotted (i.e. the last values of x_list, y_list and z_list are used).

To fix this, you want a combination of the two cases. You want to declare the figure outside of the for loop and then call plot inside of the for loop.

For example (using simple data and two for loop iterations):

x = [1, 2, 3, 4]
y = z = x
my_list = [x, [2*X for X in x]] # list of lists to be looped over

plt.figure().add_subplot(projection="3d")
for l in my_list:
    plt.plot(l, y, z)

Output:

enter image description here

  • Related