Skip to content

Instantly share code, notes, and snippets.

@cvanelteren
Created February 26, 2024 15:32
Show Gist options
  • Save cvanelteren/3ac506fa2bec130f682a5e9e2493a7a6 to your computer and use it in GitHub Desktop.
Save cvanelteren/3ac506fa2bec130f682a5e9e2493a7a6 to your computer and use it in GitHub Desktop.
dynamic_plot
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
def fill_between_3d(ax,x1,y1,z1,x2,y2,z2,mode=1,c='steelblue',alpha=0.6):
"""
Function similar to the matplotlib.pyplot.fill_between function but
for 3D plots.
input:
ax -> The axis where the function will plot.
x1 -> 1D array. x coordinates of the first line.
y1 -> 1D array. y coordinates of the first line.
z1 -> 1D array. z coordinates of the first line.
x2 -> 1D array. x coordinates of the second line.
y2 -> 1D array. y coordinates of the second line.
z2 -> 1D array. z coordinates of the second line.
modes:
mode = 1 -> Fill between the lines using the shortest distance between
both. Makes a lot of single trapezoids in the diagonals
between lines and then adds them into a single collection.
mode = 2 -> Uses the lines as the edges of one only 3d polygon.
Other parameters (for matplotlib):
c -> the color of the polygon collection.
alpha -> transparency of the polygon collection.
"""
if mode == 1:
for i in range(len(x1)-1):
verts = [(x1[i],y1[i],z1[i]), (x1[i+1],y1[i+1],z1[i+1])] + \
[(x2[i+1],y2[i+1],z2[i+1]), (x2[i],y2[i],z2[i])]
ax.add_collection3d(Poly3DCollection([verts],
alpha=alpha,
linewidths=0,
color=c))
if mode == 2:
verts = [(x1[i],y1[i],z1[i]) for i in range(len(x1))] + \
[(x2[i],y2[i],z2[i]) for i in range(len(x2))]
ax.add_collection3d(Poly3DCollection([verts],alpha=alpha,color=c))
import proplot as plt, numpy as np
x = np.linspace(-5, 5, 100)
y = np.sin(x)
layout = [[0, 1, 0],
[2, 0, 3],
[0, 4, 0]]
fig, ax = plt.subplots(layout, projection = "3d",
wspace = 0, hspace = 0,
journal = "nat1")
z = np.linspace(-1, 1, y.size)
fixed_x = np.ones(x.size) * -5
zz = 10 * z**2
for axi in ax[:-1]:
axi.plot(x, y, zs = 0)
fill_between_3d(axi, fixed_x, z, np.zeros(zz.size), fixed_x, z, zz, c = "gray")
axi.plot(fixed_x, z, zz, color = 'k')
ax.grid(False)
ax.set_zlim(0,0)
ax.set_zticks([])
ax.set_xlabel("Time (t)")
ax.set_ylabel("y")
ax[-1].plot(x, np.log(x))
ax[-1].plot(x, -np.log(x))
ax.set_box_aspect([1,1,0.01]) # hide the z-axis
ax.set_facecolor("white")
fig.savefig("test.png")
fig.show()
@cvanelteren
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment