Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib and latex beamer: Correct size

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.

like image 358
FooBar Avatar asked Sep 29 '22 11:09

FooBar


1 Answers

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,

  1. Find the line width of your Latex document in pixels. This can be done, temporarily inserting somewhere in your document, \showthe\columnwidth

  2. 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]
    
  3. 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")
    
  4. 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.

like image 166
rth Avatar answered Oct 22 '22 04:10

rth