-1

I know that I can do a 4D plot in matplotlib with the following code, with the fourth dimension shown as a colormap:

import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm

fig = plt.figure()
ax = fig.add_subplot(111,projection= '3d' )
x = np.arange(100)/ 101
y = np.sin(x) + np.cos(x)
X,Y = np.meshgrid(x,y)
Z = (X**2) / (Y**2)
A = np.sin(Z)

ax.plot_surface(X,Y, Z, facecolors=cm.Oranges(A))
plt.show()

But what if my data is not a function of the other data? How do I do this without np.meshgrid? (In other words, my Z series cannot be a function of the output of the X,Y which is the output of np.meshgrid(x,y), because Z is not a function of X and Y.)

1 Answers1

1

A surface plot is a mapping of 2D points to a 1D value, i.e. for each pair of (x,y) coordinates you need exactly one z coordinate. So while it isn't strictly necessary to have Z being a function of X and Y, those arrays to plot need to have the same number of elements.

For a plot_surface the restriction is to have X and Y as gridded 2D data. Z does not have to be 2D but needs to have the same number of elements.

This requirement can be weakened using a plot_trisurf where the only requirement is that there is a strict mapping of x,y,z, i.e. the ith value in X and Y corresponds to the ith value in Z.

In any case, even if there is no analytic function to map X and Y to Z, Z still needs to be some kind of mapping. Otherwise it is even questionable what information the resulting plot would convey.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • I was unable to do plot_surface even when I made Z a 2d array with X and Y as meshgrid, and when I tried plot_trisurf, a ValueError was raised by this exception in the source: if self.x.shape != self.y.shape or len(self.x.shape) != 1: raise ValueError. But I check x.shape and y.shape and the output was (99,), with a length of 1. So where is the error coming from then? – Abraham Horowitz Feb 23 '17 at 01:37
  • I hope you do understand that there is little I can help you with without knowning the code that produced the error. You can edit your question with a [mcve] of the code that produces the error and provide a clear problem description. – ImportanceOfBeingErnest Feb 23 '17 at 07:33