I am creating some functions to create quality figures of a standard form using matplotlib. I typically create line plots, contour plots, etc. Is there a way to pass parameters (axis limits, tick locations, etc.) to matplotlib that instructs matplotlib to use the default values of the parameters? For example
I create a class
class my_class(object):
xlimit = *something matplotlib reads as "use default"*
ylimit = *something matplotlib reads as "use default"*
linwidth = *something matplotlib reads as "use default"*
I create an instance of this class, but I only want to specify the xlimit
inst = myclass()
inst.xlimit = [0,1]
And I leave the ylimit unchanged, so matplotlib treats it as default.
I then have a function
def plot_func(x,y,fig,inst):
ax = fig.gca()
ax.set_xlim(inst.xlimit)
ax.set_ylim(inst.ylimit)
ax.plot(x,y,linewidth=inst.linwidth)
return fig
Which I can call and pass my class instance. So far this is working for me just fine, but I have to set values for all my plotting parameters in my_class().
Is there a way to set these values in my_class() to something, so that if I decide I just want matplotlib's default calculations for things like limits, ticks, labels, etc. I can still pass these 'variables' to my function plot_func() where they will all be set and I can customize what I want, and leave everything else as default?
Just to avoid these answers, I am aware of matplotlib's rc settings, this is not what I am looking for.
Since almost all things in matplotlib
are set by kwargs
, you could define all your possible optional settings as None
, unless you are going to set them manually.
Then, when you call ax.plot
or ax.set_xlim
, you can pass in your optional setting, so if the function receives the null value you get the default setting, otherwise you get your manually defined option.
class my_class(object):
xlimit = (None, None)
ylimit = (None, None)
linewidth = None
color = None
def plot_func(x,y,fig,inst):
ax = fig.gca()
ax.plot(x, y, linewidth=inst.linewidth, color=inst.color)
ax.set_xlim(inst.xlimit)
ax.set_ylim(inst.ylimit)
return fig
Then, if we call this with the default settings, we get:
x = range(5)
y = range(5)
fig, ax = plt.subplots(1)
inst1 = my_class()
plot_func(x, y, fig, inst1)
fig.savefig('default_options.png')
Otherwise, we can change any settings we like:
ax.cla()
inst2 = my_class()
inst2.xlimit = [-2, 8]
inst2.linewidth = 5
inst2.color = 'r'
plot_func(x, y, fig, inst2)
fig.savefig('custom_options.png')