[Tex/LaTex] Matplotlib’s PGF vs tikzplotlib

matplotlibpgfplotspythontikz-pgf

I want to generate some plots to be integrated into a LaTeX document compiled with pdflatex. I also want the plot font (legend, title …) to follow the settings of the LaTeX document.
My search so far gave 2 possibilites:

  • using the PGF backend in matplotlib to save raw plot data and then input it in the latex document using the PGF package
  • or using the tikzplotlib python module to convert the plot into TikZ code, compiled in LaTeX directly

What is the difference between both approaches ?
Which one is more suitable for complex matplotlib plots (many subplots with lots of data)

Best Answer

Comparison

matplotlib's PGF backend

  • Plots will be saved as PGF commands, which are lower-level and thus less suitable for manual editing. This only really matters if you aren't going to go back to Python when you need to change things. (You can also save plots directly to PDF instead.)
  • The layout will be (more or less) what the matplotlib developers intended.
  • Any matplotlib plot may be exported.

tikzplotlib

  • Plots will be saved as PGFPlots (TikZ), which is higher-level and suitable for manual editing.
  • The details of layout will primarily be determined by PGFPlots rather than matplotlib. Which is better depends on personal preference and the capabilities of the respective programs.
  • Some types of matplotlib plots may not be supported. You may have to experiment to see what works.

Other considerations

Depending on the number and complexity of your plots, inputting the PGF/PGFPlots code may be too slow. You may need to compile the PGF/PGFPlots code to PDF or another format, and input that. The TikZ externalization library may be worth looking at for this.

If you find yourself frequently switching between the LaTeX document and Python plotting code, you may want to take a look at my PythonTeX package, which allows you to include Python plotting code within the LaTeX document. With the dependency tracking features, it's possible automatically to update your plots when data changes.

Related Question