7

This code found here is an example of a 3d surface plot:

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
        linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)

ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

fig.colorbar(surf, shrink=0.5, aspect=5)

plt.show()

and yields

enter image description here

Is there a way to set the plot view so that it is perfectly normal to the x-y axis? This basically turns the 3-d plot into a 2-d one, where you can use the colourmap to judge the magnitude of the z-variable, rather than its displacement from the z=0 datum.

Jonny
  • 1,270
  • 5
  • 19
  • 31

2 Answers2

22

What you want is the ax.view_init function, with elev=90. See this answer

Edit:

after adding ax.view_init(azim=0, elev=90) to your script, I get this:

enter image description here

Community
  • 1
  • 1
jakevdp
  • 77,104
  • 11
  • 125
  • 160
  • 4
    It seems to me this will give you the yx-plane instead of the xy-plane, for me this worked: `ax.view_init(azim=-90, elev=90)` – lasofivec Jun 03 '19 at 11:42
9

You need pcolor for that:

import matplotlib.pyplot as plt
import numpy as np

dx, dy = 0.25, 0.25

y, x = np.mgrid[slice(-5, 5 + dy, dy),
                slice(-5, 5 + dx, dx)]
R = np.sqrt(x**2 + y**2)
z = np.sin(R)


z = z[:-1, :-1]
z_min, z_max = -np.abs(z).max(), np.abs(z).max()



plt.subplot()
plt.pcolor(x, y, z, cmap='RdBu', vmin=z_min, vmax=z_max)

plt.axis([x.min(), x.max(), y.min(), y.max()])
plt.colorbar()
plt.show()

enter image description here

Additional demos are here

Leb
  • 15,483
  • 10
  • 56
  • 75
  • Thanks, your answer is exactly what im looking for, but @jakevdp did technically answer my question and did so first, so I will accept his answer (-: Thanks though – Jonny Oct 12 '15 at 16:07
  • It's all good, I should've realized you're only looking for view not a whole new plot. – Leb Oct 12 '15 at 16:09
  • Yeah but your method is actually much better for what I want. Much easier to do it with a 2d plot, just didn't know it will be possible. – Jonny Oct 12 '15 at 16:11