How do I limit the border size on a matplotlib graph?
-
05-07-2019 - |
Question
I'm making some pretty big graphs, and the whitespace in the border is taking up a lot of pixels that would be better used by data. It seems that the border grows as the graph grows.
Here are the guts of my graphing code:
import matplotlib
from pylab import figure
fig = figure()
ax = fig.add_subplot(111)
ax.plot_date((dates, dates), (highs, lows), '-', color='black')
ax.plot_date(dates, closes, '-', marker='_', color='black')
ax.set_title('Title')
ax.grid(True)
fig.set_figheight(96)
fig.set_figwidth(24)
Is there a way to reduce the size of the border? Maybe a setting somewhere that would allow me to keep the border at a constant 2 inches or so?
Solution
Since it looks like you're just using a single subplot, you may want to skip add_subplot
and go straight to add_axes
. This will allow you to give the size of the axes (in figure-relative coordinates), so you can make it as large as you want within the figure. In your case, this would mean your code would look something like
import matplotlib.pyplot as plt
fig = plt.figure()
# add_axes takes [left, bottom, width, height]
border_width = 0.05
ax_size = [0+border_width, 0+border_width,
1-2*border_width, 1-2*border-width]
ax = fig.add_axes(ax_size)
ax.plot_date((dates, dates), (highs, lows), '-', color='black')
ax.plot_date(dates, closes, '-', marker='_', color='black')
ax.set_title('Title')
ax.grid(True)
fig.set_figheight(96)
fig.set_figwidth(24)
If you wanted, you could even put the parameters to set_figheight
/set_figwidth
directly in the figure()
call.
OTHER TIPS
Try the subplots_adjust
API:
subplots_adjust(*args, **kwargs)
fig.subplots_adjust(left=None, bottom=None, right=None, wspace=None, hspace=None)
Update the SubplotParams with kwargs (defaulting to rc where None) and update the subplot locations