简体   繁体   中英

Set matplotlib view to be normal to the x-y plane in Python

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

在此输入图像描述

Is there a way to set the plot view so that it is perfectly normal to the xy 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.

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:

在此输入图像描述

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()

在此输入图像描述

Additional demos are here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM