Set height and width of a shape created with plt.subplots in matplotlib?

In matplotlib, I know how to set the height and width and DPI of a shape:

fig = plt.figure(figsize=(4, 5), dpi=100) 

However, it seems that if I want to create small multiple plots, I cannot create such a figure, I should use this:

 fig, subplots = plt.subplots(nrows=4, ncols=4) 

How to set the height and width and DPI of a figure created with subtasks like this?

+3
python matplotlib
source share
2 answers

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 to wrap it in a function and use 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 

Using:

 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-'); 
+2
source share

In fact, you can specify height and widthplt.savefig ("Desktop / test.png", dpi = 500), although it is not listed as a keyword in the help (I think it is passed to a digit (?)):

 fig,axs=plt.subplots(nrows,ncols,figsize=(width,height)) 

For some reason, however, dpi is ignored. However, you can use it when saving a shape when it matters:

 plt.savefig('test.png',dpi=1000) 
0
source share

All Articles