Reputation: 16518
There were several questions asked about the integration of matplotlib/Python and latex, but I couldn't find the following:
When I include the savefig()
created pdf files in latex, I always to
includegraphics[scale=0.5]{myFile.pdf}
And the scale is usually around 0.4
or 0.5
. Given that I'm creating A5 beamer slides, what is the correct way to generate pdf files in the correct size for that, such that I don't need to specify that in latex?
Note that these are not full-size image-only beamer slides, it needs to be somewhat smaller to allow header,footer and caption.
Upvotes: 7
Views: 4343
Reputation: 11199
See this matplotlib cookbook for creating publication quality plots for Latex. Essentially, in order to keep a constant size of all figure attributes (legend, etc) scaling when importing figures in latex should be avoided. The proposed approach is the following,
Find the line width of your Latex document in pixels. This can be done, temporarily inserting somewhere in your document, \showthe\columnwidth
Define a helper functions in python that will be used to compute the figure size,
def get_figsize(columnwidth, wf=0.5, hf=(5.**0.5-1.0)/2.0, ):
"""Parameters:
- wf [float]: width fraction in columnwidth units
- hf [float]: height fraction in columnwidth units.
Set by default to golden ratio.
- columnwidth [float]: width of the column in latex. Get this from LaTeX
using \showthe\columnwidth
Returns: [fig_width,fig_height]: that should be given to matplotlib
"""
fig_width_pt = columnwidth*wf
inches_per_pt = 1.0/72.27 # Convert pt to inch
fig_width = fig_width_pt*inches_per_pt # width in inches
fig_height = fig_width*hf # height in inches
return [fig_width, fig_height]
Figures are then produced with,
import matplotlib
import matplotlib.pyplot as plt
# make sure that some matplotlib parameters are identical for all figures
params = {'backend': 'Agg',
'axes.labelsize': 10,
'text.fontsize': 10 } # extend as needed
matplotlib.rcParams.update(params)
# set figure size as a fraction of the columnwidth
columnwidth = # value given by Latex
fig = plt.figure(figsize=get_figsize(columnwidth, wf=1.0, hf=0.3)
# make the plot
fig.savefig("myFigure.pdf")
Finally this figure is imported in Latex without any scaling,
\includegraphics{myFigure.pdf}
thus ensuring, among other things, that, say, a 12pt
text in matplotlib corresponds to the same font size in the Latex document.
Upvotes: 5
Reputation: 371
You'd be better off specifying the absolute size of image that you want, rather than the scale. (You could specify height, if that's more convenient, and can use cm as units)
\includegraphics[height=4in]{myFile.pdf}
Better yet, define a macro that inserts your images. Here's one that inserts an image without wrapping it in a figure (which includes a caption, padding space, etc.)
\newcommand{\plotstandard}[1]{\centerline{\includegraphics[height=4in]{#1}}}
which is called using
\plotstandard{myFile.pdf}
Upvotes: 0