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.
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.
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