Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Improve subplot size/spacing with many subplots in matplotlib

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) 
like image 617
mcstrother Avatar asked Jun 30 '11 21:06

mcstrother


People also ask

How do I increase the spacing between subplots in Matplotlib?

We can use the plt. subplots_adjust() method to change the space between Matplotlib subplots. The parameters wspace and hspace specify the space reserved between Matplotlib subplots. They are the fractions of axis width and height, respectively.

How do I reduce the gap between subplots?

subplots_adjust() Method to Change Space Between Subplots in Matplotlib. We can use the plt. subplots_adjust() method to change the space between Matplotlib subplots. wspace and hspace specify the space reserved between Matplotlib subplots.

How do you make subplots not overlap?

Often you may use subplots to display multiple plots alongside each other in Matplotlib. Unfortunately, these subplots tend to overlap each other by default. The easiest way to resolve this issue is by using the Matplotlib tight_layout() function.


1 Answers

Try using plt.tight_layout

As a quick example:

import matplotlib.pyplot as plt  fig, axes = plt.subplots(nrows=4, ncols=4) fig.tight_layout() # Or equivalently,  "plt.tight_layout()"  plt.show() 

Without Tight Layout

enter image description here


With Tight Layout enter image description here

like image 194
Joe Kington Avatar answered Oct 21 '22 11:10

Joe Kington