简体   繁体   中英

How you can define the dimensions of a subplot (in inches) within a figure with matplotlib?

My figure has dimensions of figsize=(10,10) and one subplot within it. How can i define the dimension of the subplot to be 8 inches W x 8 inches H regardles the data range the subplot it shows?

EDIT: The reason I am searching for this is that I am trying to create some plots for publication. So I need my plots to have a fixed width and height to be able to be inserted to the manuscrpipt seamsly.

Here's the striped down code:

map_size = [8,8]
fig, ax = plt.subplots(1,1,figsize=map_size)
ax.plot(data)
fig.savefig('img.png', dpi=300,)  # figure is the desired size, subplot seems to be scaled to fit to fig

One option is to use fig.subplots_adjust to set the size of the subplot within the figure. The arguments left , right , bottom and top are fractional units (of the total figure dimensions). So, for an 8x8 subplot in a 10x10 figure, right - left = 0.8 , etc.:

import matplotlib.pyplot as plt

fig=plt.figure(figsize=(10.,10.))
fig.subplots_adjust(left=0.1,right=0.9,bottom=0.1,top=0.9)

ax=fig.add_subplot(111)

Doing it like this, you would have to manually change the left, right, bottom and top values if you change the figure size.

I guess you could build that calculation into your code:

import matplotlib.pyplot as plt

subplotsize=[8.,8.]
figuresize=[10.,10.]   

left = 0.5*(1.-subplotsize[0]/figuresize[0])
right = 1.-left
bottom = 0.5*(1.-subplotsize[1]/figuresize[1])
top = 1.-bottom

fig=plt.figure(figsize=(figuresize[0],figuresize[1]))
fig.subplots_adjust(left=left,right=right,bottom=bottom,top=top)

ax=fig.add_subplot(111)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM