简体   繁体   中英

set axis limits on matplotlib 3d plot (python)

I want to set axis limits in matplotlib 3D plot.

so I used 'set_zlim', but happened some error on my results.

how can I do?

在此处输入图像描述


from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure(figsize=(10, 5))
ax = fig.gca( fc='w', projection='3d')

for hz, freq, z in zip(all_hz, all_freq,all_amp):
    x = hz
    y = freq
    z = z
    
    ax.plot3D(x, y, z)
    ax.set_ylim(-10,15000)
    ax.set_zlim(0,0.1)

plt.show()

This seem to be a flaw in the toolkit due to the perspective. The data is plotted without being cropped to the correct limits. You can always slice the data to the correct values:

import numpy as np
# define limits
ylim = (-10,15000)
zlim = (0,0.1)

x = hz 
# slicing with logical indexing
y = freq[ np.logical_and(freq >= ylim[0],freq <= ylim[1] ) ]
# slicing with logical indexing
z = z[ np.logical_and(z >= zlim[0],z <= zlim[1] ) ]
    
ax.plot3D(x, y, z)
ax.set_ylim(ylim) # this shouldn't be necessary but the limits are usually enlarged per defailt
ax.set_zlim(zlim) # this shouldn't be necessary but the limits are usually enlarged per defailt

The set_ylim() and set_zlim() methods simply define the upper and lower boundries of the axes. They don't trim your data for you. To do that, you have to add a conditional statement like below to trim your data:

from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure(figsize=(10, 5))
ax = fig.gca(fc='w', projection='3d')

for hz, freq, z in zip(all_hz, all_freq, all_amp):
    if freq < 15000 and z < 0.1:
        x = hz
        y = freq
        z = z

        ax.plot3D(x, y, z)
        ax.set_ylim(-10, 15000)
        ax.set_zlim(0, 0.1)

plt.show()

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