In matplotlib, I know how to set the height and width and DPI of a figure:
fig = plt.figure(figsize=(4, 5), dpi=100)
However, it seems that if I want to create small multiple plots, I can't create a figure like this, I have to use this:
fig, subplots = plt.subplots(nrows=4, ncols=4)
How can I set the height and width and DPI of a figure created with subplots like this?
To change figure size of more subplots you can use plt. subplots(2,2,figsize=(10,10)) when creating subplots.
Set the Height and Width of a Figure in Matplotlib Instead of the figsize argument, we can also set the height and width of a figure. These can be done either via the set() function with the figheight and figwidth argument, or via the set_figheight() and set_figwidth() functions.
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.
You can actually specify height and widthplt.savefig('Desktop/test.png',dpi=500) , even though it's not listed as keyword in the help (I think it is passed on to the figure call(?)):
fig,axs=plt.subplots(nrows,ncols,figsize=(width,height))
For some reason, dpi is ignored though. However, you can use it when saving the figure, when it is important:
plt.savefig('test.png',dpi=1000)
A working example of the gridspec module:
import matplotlib.pyplot as plt
from matplotlib import gridspec
fig = plt.figure(figsize=(18,18))
gs = gridspec.GridSpec(3, 3)
ax1 = fig.add_subplot(gs[0,:])
ax1.plot([1,2,3,4,5], [10,5,10,5,10], 'r-')
ax2 = fig.add_subplot(gs[1,:-1])
ax2.plot([1,2,3,4], [1,4,9,16], 'k-')
ax3 = fig.add_subplot(gs[1:, 2])
ax3.plot([1,2,3,4], [1,10,100,1000], 'b-')
ax4 = fig.add_subplot(gs[2,0])
ax4.plot([1,2,3,4], [0,0,1,1], 'g-')
ax5 = fig.add_subplot(gs[2,1])
ax5.plot([1,2,3,4], [1,0,0,1], 'c-')
gs.update(wspace=0.5, hspace=0.5)
plt.show()
But I prefer wrapping it in a function and using it like this:
def mySubplotFunction(fig,gs,x,y,c,ax=None):
if not ax:
ax = fig.add_subplot(gs)
ax.plot(x, y, c)
return fig, ax
Usage:
fig2 = plt.figure(figsize=(9,9))
fig2, ax1 = mySubplotFunction(fig2,gs[0,:],[1,2,3,4,5],[10,5,10,5,10],'r-');
fig2, ax2 = mySubplotFunction(fig2,gs[1,:-1],[1,2,3,4],[1,4,9,16],'k-');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With