hatmatrix
hatmatrix

Reputation: 44862

matplotlib assign multiple variables to axes instance with single command

Was there a way to pass a dictionary to an axes method to set instance variables all at once without calling .set_xlim(), .set_ylim(), and so on individually? I know Matlab has this feature and I thought Matplotlib as well but cannot find the documentation.

Upvotes: 2

Views: 1160

Answers (1)

Joe Kington
Joe Kington

Reputation: 284552

It's plt.setp (Also see getp).

As a quick example:

import matplotlib.pyplot as plt

linestyle = dict(color='red', marker='^', linestyle='--', linewidth=2)

fig, ax = plt.subplots()
line, = ax.plot(range(10))

plt.setp(ax, xlim=[-1, 12], ylim=[-5, 12], xlabel='X-axis')
plt.setp(line, **linestyle)

plt.show()

enter image description here

setp and getp are "matlab-isms", so a lot of people feel that they are "unpythonic" and shouldn't be used unless absolutely necessary.

Obviously, you can do all of this in other ways (e.g. setting the axis limits with ax.axis([xmin, xmax, ymin, ymax]) or just expanding the linestyle dict when calling plot).

setp is still very useful, though. It automatically operates on sequences of artists, so you can do things like plt.setp([ax1, ax2, ax3], **parameters). This is especially handy for things like ticks and ticklabels, where you're often operating of a bunch of artists at once.

It also allows for easy introspection of matplotlib artists. Try calling things like plt.setp(ax) to see a list of all parameters or plt.setp(line, 'marker') to see a list of all valid arguments to line.set_marker.

Upvotes: 1

Related Questions