tikzplotlib

repository·main·Indexed 25 days ago

https://github.com/nschloe/tikzplotlib

A Python tool that converts matplotlib figures into PGFPlots/TikZ code for inclusion in LaTeX or ConTeXt documents. It allows users to retain data structures like axes and data points rather than exporting raw images. Key features include the save() and get_tikz_code() functions, support for different TeX flavors, and a clean_figure() utility to optimize output by simplifying curves and pruning points. Note that 3D plots cannot be converted and will result in errors.

Tokens
2.5K
Snippets
6
Records
16
Agent score
83%

What's inside tikzplotlib

  1. Include TikZ output in your TeX document

    main

    Once you have generated a .tex file, include it in your LaTeX source using \input{}.

    Required LaTeX Preamble Configuration: Ensure your document header includes pgfplots and proper Unicode support:

    \usepackage[utf8]{inputenc}
    \usepackage{pgfplots}
    \DeclareUnicodeCharacter{2212}{−}
    \usepgfplotslibrary{groupplots,dateplot}
    \usetikzlibrary{patterns,shapes.arrows}
    \pgfplotsset{compat=newest}
  2. How the Axes class manages TikZ conversion

    main

    The Axes class is responsible for converting a Matplotlib Axes object into PGFPlots code. It extracts various properties from the Matplotlib object, including:

    • Titles: Plot title, x-label, and y-label (with support for LaTeX texification and color).
    • Limits and Scaling: Axis limits (xmin, xmax, ymin, ymax), axis inversion (x dir=reverse), and logarithmic scaling (xmode=log, ymode=log) including the log base.
    • Ticks and Labels: Major and minor ticks, tick labels, tick rotation, horizontal alignment, and tick direction (tick align=outside, tick align=center, or tick align=inside).
    • Gridlines: Major and minor gridlines (xmajorgrids, xminorgrids, etc.) and their styles.
    • Appearance: Axis line styles, background color, and axis position (e.g., axis x line=top).
    • Dimensions: Aspect ratio and explicit width/height settings.
    • Colorbars: Detection and conversion of associated colorbars, including orientation, limits, and colormaps.
    • Subplots: Handling of subplots using groupplots logic.

    Note: Axes that host a colorbar are treated implicitly by the associated axis and are skipped by the Axes class to avoid duplication.

  3. Hatch mapping from Matplotlib to TikZ patterns

    main

    When using tikzplotlib, Matplotlib hatches are mapped to TikZ patterns. Note that tikzplotlib currently has limitations regarding hatch density and complex hatch strings.

    Supported single-character hatches and their TikZ equivalents:

    • -: horizontal lines
    • |: vertical lines
    • /: north east lines
    • \: north west lines
    • +: grid
    • x: crosshatch
    • .: crosshatch dots
    • *: fivepointed stars
    • o: sixpointed stars
    • O: bricks

    Limitations:

    • Multi-character hatches: If you use a multi-character hatch (e.g., // to increase density), tikzplotlib will only use the first character and issue a warning. Only single-character hatches are fully supported.
    • Bad correspondences: The hatches o and O are noted as having poor PGF counterparts.
    • Requirements: Using these patterns requires the TikZ library \usetikzlibrary{patterns}, which tikzplotlib attempts to add automatically.
  4. Use different flavors for LaTeX or ConTeXt

    main

    You can specify the target TeX engine using the flavor argument in tikzplotlib.save().

    • For LaTeX: flavor="latex" (default)
    • For ConTeXt: flavor="context"

    You can also retrieve the required preamble for these flavors using tikzplotlib.Flavors.latex.preamble() or tikzplotlib.Flavors.context.preamble().

  5. Convert matplotlib figures to TikZ files

    main

    To convert a matplotlib figure to a .tex file, use tikzplotlib.save(filename). This creates a PGFPlots-based TeX file that can be included in LaTeX or ConTeXt documents.

    If you need the TikZ code as a string instead of saving it to a file, use tikzplotlib.get_tikz_code().

    import matplotlib.pyplot as plt
    import numpy as np
    import tikzplotlib
    
    # ... create your plot ...
    
    tikzplotlib.save("test.tex")
  6. Clean matplotlib figures before exporting

    main

    Use tikzplotlib.clean_figure() before calling save() to optimize the output. This command removes points outside the axes limits, simplifies curves, and reduces point density for the target resolution. This is useful for reducing file size and complexity.

    import matplotlib.pyplot as plt
    import tikzplotlib
    
    # ... do your plotting ...
    
    tikzplotlib.clean_figure()
    tikzplotlib.save("test.tex")
  7. Simplify 3D lineplots with clean_figure()

    main

    The clean_figure() function also supports 3D lineplots (using mpl_toolkits.mplot3d). It will prune points outside the visible 3D bounding box and simplify the path to reduce the complexity of the exported TikZ code.

    from tikzplotlib import get_tikz_code, cleanfigure
    import matplotlib.pyplot as plt
    import numpy as np
    from mpl_toolkits import mplot3d
    
    theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
    z = np.linspace(-2, 2, 100)
    r = z ** 2 + 1
    x = r * np.sin(theta)
    y = r * np.cos(theta)
    
    fig = plt.figure()
    ax = fig.add_subplot(111, projection="3d")
    ax.plot(x, y, z)
    ax.set_xlim([-2, 2])
    ax.set_ylim([-2, 2])
    ax.set_zlim([-2, 2])
    ax.view_init(30, 30)
    
    raw = get_tikz_code(fig)
    
    clean_figure(fig)
    clean = get_tikz_code()
    
    # Verify reduction in complexity
    numLinesRaw = raw.count("\n")
    numLinesClean = clean.count("\n")
    assert numLinesRaw - numLinesClean == 14
  8. Use draw_image to include images in TikZ output

    main

    The draw_image function is an internal utility used by tikzplotlib to convert Matplotlib image objects (like those created by plt.imshow) into PGFPlots code. It handles saving the image data to a file (typically as a .png) and generating the corresponding LaTeX \addplot graphics command using \pgfimage to ensure compatibility.

    When an image is processed:

    1. It is saved to a temporary file.
    2. The image extent (coordinates) is extracted.
    3. A TikZ command is generated using the configured float format (e.g., from the data dictionary) and the POSIX-style file path.
  9. Clean matplotlib figures with clean_figure()

    main

    Use clean_figure() to prepare a Matplotlib figure for TikZ export. This function minimizes the number of data points required for the resulting TikZ figure by applying path simplification and pruning points outside the visible axis limits.

    Warning: This is an impure function; it modifies the Matplotlib figure object directly.

    Parameters

    • fig (Matplotlib figure handle, optional): The figure to clean. If None or 'gcf', the current figure is used.
    • target_resolution (int, list, or np.array, optional): The target resolution in PPI (Pixels Per Inch).
      • If a scalar integer is provided, it is assumed to be square for both axes.
      • If a list or np.array is provided, it is interpreted as [Height, Width].
      • Default is 600.
    • scale_precision (float, optional): A scalar value indicating precision when scaling down. Default is 1.0.
    from tikzplotlib import get_tikz_code, cleanfigure
    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.linspace(1, 100, 20)
    y = np.linspace(1, 100, 20)
    
    fig, ax = plt.subplots(1, 1, figsize=(5, 5))
    ax.plot(x, y)
    ax.set_ylim([20, 80])
    ax.set_xlim([20, 80])
    
    # Get raw TikZ code before cleaning
    raw = get_tikz_code()
    
    # Clean the figure (modifies fig in place)
    clean_figure(fig)
    
    # Get TikZ code after cleaning
    clean = get_tikz_code()
    
    # The clean version will have significantly fewer lines/points
    print("Difference in lines:", raw.count("\n") - clean.count("\n"))