I have written a code that generates a 3D bar plot and a contour plot in Matplotlib, illustrating the distribution of a random walker’s position on a plane. However, I want to use Plotly for its interactive interface. Although I can plot the contour plot using go.Histogram2dContour()
, I don’t know how to plot a 3D bar plot in Plotly.
Can anyone help me with this?
I’ve attached the code and the plot that I generated using Matplotlib.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.animation import FuncAnimation
stepsize = 0.5
num_steps = 200
num_trials = 10**3
final_position = []
for _ in range(num_trials):
pos = np.array([0, 0])
path = []
for i in range(num_steps):
pos = pos + np.random.normal(0, stepsize, 2)
path.append(pos)
final_position.append(np.array(path))
x = [final_position[i][:,0] for i in range(len(final_position))]
y = [final_position[j][:,1] for j in range(len(final_position))]
x_flattened = np.array(x).flatten()
y_flattened = np.array(y).flatten()
hist_fig = plt.figure(figsize=(14, 6), dpi = 200)
# 3D Histogram subplot
ax1 = hist_fig.add_subplot(121, projection='3d')
hist, xedges, yedges = np.histogram2d(x_flattened, y_flattened, bins=100)
xpos, ypos = np.meshgrid(xedges[:-1] + 0.25, yedges[:-1] + 0.25)
xpos = xpos.flatten('F')
ypos = ypos.flatten('F')
zpos = np.zeros_like(xpos)
dx = dy = 0.5 * np.ones_like(zpos)
dz = hist.flatten()
colors = plt.cm.magma(dz / dz.max())
ax1.bar3d(xpos, ypos, zpos, dx, dy, dz, color=colors, zsort='average')
ax1.set_xlabel('X')
ax1.set_ylabel('Y')
ax1.set_zlabel('Frequency')
ax1.set_title("Distribution of Walker's position on the xy plane")
cbar = plt.colorbar(cm.ScalarMappable(norm=plt.Normalize(dz.min(), dz.max()), cmap='magma'), ax=ax1, shrink=0.6, pad=0.12)
# Contour plot subplot
ax2 = hist_fig.add_subplot(122)
hist, xedges, yedges = np.histogram2d(x_flattened, y_flattened, bins=100)
xcenters = (xedges[:-1] + xedges[1:]) / 2
ycenters = (yedges[:-1] + yedges[1:]) / 2
X, Y = np.meshgrid(xcenters, ycenters)
contour = ax2.contourf(X, Y, hist.T, cmap='magma', levels = 25)
ax2.set_xlabel('X')
ax2.set_ylabel('Y')
ax2.set_xlim(min(xcenters), max(xcenters))
ax2.set_ylim(min(ycenters), max(ycenters))
ax2.set_title("Contour plot of the Walker's position on the xy plane")
ax2.set_aspect('equal')
cbar = plt.colorbar(contour, ax=ax2, shrink=0.6)
plt.show()
The plot will look like this