I am righteously confused with the coding paradigms offered by matplotlib. I am using code like this below to plot some data:
fig=plt.figure(figsize=fig_size) # plt=pyplot defined above
axes1 = fig.add_subplot(111)
axes1.plot(temp, depth, 'k-')
axes1.set_ylim(-600,0)
axes1.set_ylabel(r'Depth $(m)$')
axes1.set_xlim(0,80)
axes1.set_xlabel(r'Temperature (\textcelsius)')
axes1.set_xticks(np.arange(0,100,20))
axes1.grid(True)
plt.savefig(savedir + 'plot.svg', transparent=True)
I’d rather use mpl’s object-oriented style than the pylab convenience functions. So question is if I only want to plot one curve, non-interactively, am I using the right figure creation style? (lines 1 & 2). It seems like a lot of separate calls are needed to format the axis labels and so on.
What you’re doing looks fine. (And I agree, it’s much cleaner to only use
pyplotfor figure creation and use the OO API for everything else.)If you’d prefer to make the figure and axes in one call, use
plt.subplots.Also, I find it’s a bit cleaner to use
fig.savefiginstead ofplt.savefig. It won’t matter in this case, but that way you avoid having to worry about which figure is “active” in the state-machine interface.For one last thing, you could set the x and y limits with a single call to
axes1.axis(...). This is purely a matter of preference.set_xlimandset_ylimare arguably a more readable way of doing it.The “setters” and “getters” are annoying, but date from when python didn’t have properties, if I recall correctly. They’ve been kept as the main methods partly for backwards compatibility, and partly so that “matlab-isms” like
plt.setpare easier to write. In fact, if you wanted you could doThis avoids having to do three separate calls to set the xlabel, ylabel, and xticks. However, I personally tend to avoid it. I find it’s better to be slightly more verbose in most cases. If you find it cleaner or more convenient, though, there’s nothing wrong with using
setp.As an example of how I’d write it: