Issue
I have a 2D numpy matrix that I would like to plot as a 3D surface plot using matplotlib.
For each X between X0 and Xend and Y between Y0 and Yend, I would like to plot a dot with a Z-value equal to matrix[X,Y].
I suppose that I could manually unroll the matrix and produce an array of X values, an array of Y values, and a 1D array of Z values, but this seems awkward and inefficient.
I tried
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
#plt.matshow(bias_array)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(range(X0,Xend), range(Y0,Yend), bias_array[X0:Xend,Y0:Yend], marker='o')
but this produces
shape mismatch: objects cannot be broadcast to a single shape. Mismatch is between arg 0 with shape (5,) and arg 2 with shape (25,).
(note that both the X and Y ranges are 5 for this example case)
because matplotlib does not know to go into the matrix and pick out X,Y for each data point.
Solution
You could use the np.meshgrid
function.
numpy docs stackoverflow answer
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
# Dummy data
X0, Xend = 0, 5
Y0, Yend = 0, 5
bias_array = np.random.rand(10, 10)
# This creates 2D coordinate arrays for X and Y
X, Y = np.meshgrid(range(X0, Xend), range(Y0, Yend))
Z = bias_array[X0:Xend, Y0:Yend]
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z)
plt.show()
Answered By - ArjunSahlot
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.