Search code examples
pythonmatplotlibaxes

Is there a way to specify x y and z limits in matplotlib plots in one command instead of 3 separate lines?


I am developing a program that needs to automatically switch from 2D to 3D plots in matplotlib. So I am looking for a way to not have many if statements to decide between 2 and 3d

I have looked at postings here as well as matplotlib documentation page and I didnt find anything

currently the plot axes limits are set using

ax.set_xlim(minvals[0],maxvals[0])  
ax.set_ylim(minvals[1],maxvals[1])

then if it is 3D I have a separate list

ax.set_xlim3d(min_vals[0],max_vals[0])
ax.set_ylim3d(min_vals[1],max_vals[1])
ax.set_zlim3d(min_vals[2],max_vals[2]) 

It seems logical to have a way to have something like ax.set_lims(min_vals, max_vals) whether for 2d or 3d. Is there a way to do this?


Solution

  • Use the method .set(**kwargs) like this:

    ax.set(**{'xlim3d': [min_vals[0],max_vals[0]], \
              'ylim3d': [min_vals[1],max_vals[1]], \
              'zlim3d': [min_vals[2],max_vals[2]]})
    

    Usually when you want to set a property xxxx with .set_xxxx(), you use:

    ax.set_xxxx(some_value)
    

    With .set(**kwargs) I explain above, when .set_xxxx(some_value) is added, it becomes:

    ax.set(**{'xlim3d': [min_vals[0],max_vals[0]], \
              'ylim3d': [min_vals[1],max_vals[1]], \
              'zlim3d': [min_vals[2],max_vals[2]], \
              'xxxx': some_value})