[Tex/LaTex] How to include a graph from python in latex text

floatspythontikz-pgf

How would I include a figure from python in LaTeX, in order to use the same font in the text and to adjut the size.

If you can include the code that would be great.

Sorry, if my question is a bit simple.

The last two lines

mpl.use("pgf")
mpl.rcParams.update(pgf_with_latex)

Are they ment to be in python code?

If so, what package need to be used with?

Best Answer

If you use matplotlib you can use something like the following:

pgf_with_latex = {                      # setup matplotlib to use latex for output
    "pgf.texsystem": "pdflatex",        # change this if using xetex or lautex
    "text.usetex": True,                # use LaTeX to write all text
    "font.family": "serif",
    "font.serif": [],                   # blank entries should cause plots 
    "font.sans-serif": [],              # to inherit fonts from the document
    "font.monospace": [],
    "axes.labelsize": 10,
    "font.size": 10,
    "legend.fontsize": 8,               # Make the legend/label fonts 
    "xtick.labelsize": 8,               # a little smaller
    "ytick.labelsize": 8,
    "figure.figsize": [your-width,your-height],     # default fig size of 0.9 textwidth
    "pgf.preamble": [
        r"\usepackage[utf8]{inputenc}",    # use utf8 input and T1 fonts 
        r"\usepackage[T1]{fontenc}",        # plots will be generated 
        ]                                   # using this preamble
    }
mpl.use("pgf")
mpl.rcParams.update(pgf_with_latex)

Change the your-width and your-height in the above to the desired dimensions in inch. To the preamble add anything you need to reproduce the look of your document (e.g. r"\usepackage{lmodern} if you use lmodern). After that you should be able to use savefig('name.pdf') to save the plot as a pdf and import it into LaTeX. If everything in the above was set correctly it should look like perfectly belonging to your document.

If you don't want to adapt your preamble here every time you can as well use savefig(name.pgf) and include the resulting file in your document via \input. This way you don't have to use your actual preamble in Python as the font is set by the TeX interpreter. But notice that this way compilation of your document takes a lot more time than if you include a pdf.

You can create a new figure with custom size with plt.figure(figsize=[width,height]) (this way you don't have to update the rcParams with the correct size).