Very similar to this question but with the difference that my figure can be as large as it needs to be.
I need to generate a whole bunch of vertically-stacked plots in matplotlib. The result will be saved using figsave and viewed on a webpage, so I don't care how tall the final image is as long as the subplots are spaced so they don't overlap.
No matter how big I allow the figure to be, the subplots always seem to overlap.
My code currently looks like
import matplotlib.pyplot as plt
import my_other_module
titles, x_lists, y_lists = my_other_module.get_data()
fig = plt.figure(figsize=(10,60))
for i, y_list in enumerate(y_lists):
plt.subplot(len(titles), 1, i)
plt.xlabel("Some X label")
plt.ylabel("Some Y label")
plt.title(titles[i])
plt.plot(x_lists[i],y_list)
fig.savefig('out.png', dpi=100)
Try using
plt.tight_layout
As a quick example:
Without Tight Layout
With Tight Layout
You could try the subplot_tool()
You can use
plt.subplots_adjust
to change the spacing between the subplots (source)call signature:
The parameter meanings (and suggested defaults) are:
The actual defaults are controlled by the rc file
The plt.subplots_adjust method:
or
The size of the picture matters.
"I've tried messing with hspace, but increasing it only seems to make all of the graphs smaller without resolving the overlap problem."
Thus to make more white space and keep the sub plot size the total image needs to be bigger.
Similar to
tight_layout
matplotlib now (as of version 2.2) providesconstrained_layout
. In contrast totight_layout
, which may be called any time in the code for a single optimized layout,constrained_layout
is a property, which may be active and will optimze the layout before every drawing step.Hence it needs to be activated before or during subplot creation, such as
figure(constrained_layout=True)
orsubplots(constrained_layout=True)
.Example:
constrained_layout may as well be set via
rcParams
See the what's new entry and the Constrained Layout Guide
I found that subplots_adjust(hspace = 0.001) is what ended up working for me. When I use space = None, there is still white space between each plot. Setting it to something very close to zero however seems to force them to line up. What I've uploaded here isn't the most elegant piece of code, but you can see how the hspace works.