Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
894 views
in Technique[技术] by (71.8m points)

matplotlib - pad_inches=0 and bbox_inches="tight" makes the plot smaller than declared figsize

I am producing a publication-quality plot to be embedded in latex and I would like to be very precise in terms of sizes and fonts (so that fonts are of the same size in the article as in the plot). To prevent the plot from scaling in latex I would like to have it exact size, but I cannot. Here is my code:

import matplotlib.pyplot as plt
from matplotlib import rc, rcParams
from numpy import sin

rc('text', usetex=True)
rc('font', family='serif', serif='Computer Modern Roman', size=8)
rc('legend', fontsize=10)

width_in = 5
fig = plt.figure(1, figsize=(width_in, 2))
ax = fig.add_subplot(111)
ax.plot(range(0,100), sin(range(0,100)))

fig.tight_layout()
fig.savefig('test.eps', bbox_inches='tight', pad_inches=0)
plt.close()

The problem is with bbox_inches='tight' and pad_inches=0. Adding those options makes my plot 4.76 inches wide instead of declared 5 inches. But I want them to save space. So how to solve it?

Edit: Well, the answers suggest to remove bbox_inches='tight' and pad_inches=0 and use just the tight_layout(). Then the images is of right size, however it has still some white padding around. I can remove it with fig.tight_layout(pad=0), but then the figure title it moved inside the box, which looks ugly. On the other hand I can use tight_layout(rect=[...]) and obtain the desired result, but it is a manual work to get the numbers right - I don't like it. Thus, currently I don't see any easy and general solution to my problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem you are having is that bbox_inches='tight' just removes all of the extra white space around your figure, it does not actually re-arrange anything in your figure, after it has been rendered.

You might need to tweak the parameters you pass to tight_layout (tutorial) to get your desired effect.

Hopefully this gets you pointed in the right direction.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...