0

I have a practical question commonly seen in Matplotlib, that many times I will have to write

ax.set_xlim([-5, 5])
ax.set_ylim([-5, 5])
ax.set_zlim([0, 5])

I am wonder is there a way of looping through them?

I searched that there is one possible way to loop them is to use eval(). But I haven't figure out exactly it can be done with it.

Is there a clever way of looping this? Thanks!

2
  • these are three different functions with 3 different inputs (2 unique in this case)...writing a loop would actually almost certainly be more code than this or at minimum contain basically the exact same code in another form... what do you mean by loop? Commented Jun 7, 2020 at 7:04
  • Since you'll need to provided upper and lower limits for all three axes in any case, whatever you come up with will still have 6 inputs - you could write something that allows you to set all limits in one go, similar to ax.set_lims([-5, 5], [-5, 5], [0, 5]) but I don't think that all that much more clear. And how often do you have to set limits for your axes that you think this is worth the effort? Commented Jun 7, 2020 at 7:19

1 Answer 1

1

If this is all you're doing, it's probably easiest to type it out every time. You can save a tiny bit of typing, for some loss of clarity, by setting the x and y limits with a single call; but the z limits remain separate:

ax.axis([xmin, xmax, ymin, ymax])
ax.set_zlim([zmin, zmax])

If you're doing this very often, you could create a utilities module, and start collecting functions for code snippets you use a lot.

E.g. you might find it useful to have a single function to create the 3D projection, and set the limits and labels:

def setup3d(fig, lims=None, labels=None):
    ax = fig.gca(projection='3d')
    if lims:
        ax.set_xlim(*lims[0:2])
        ax.set_ylim(*lims[2:6])
        ax.set_zlim(*lims[4:6])
    if labels:
        ax.set_xlabel(labels[0])
        ax.set_ylabel(labels[1])
        ax.set_zlabel(labels[2])
    return ax

fig = plt.figure()
ax = setup3d(fig, [-2, 2, 1, 5, -5, 5], ['my X', 'YYY' ,'Z'])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.