### Clean 2D Lineplot for TikZ Export Source: https://tikzplotlib.readthedocs.io/ Demonstrates how to use `clean_figure` to reduce the number of points in a 2D Matplotlib plot before exporting to TikZ. This is useful for optimizing the generated TikZ code size. The example compares the line count of the raw and cleaned TikZ output. ```python from tikzplotlib import get_tikz_code, cleanfigure x = np.linspace(1, 100, 20) y = np.linspace(1, 100, 20) with plt.rc_context(rc=RC_PARAMS): fig, ax = plt.subplots(1, 1, figsize=(5, 5)) ax.plot(x, y) ax.set_ylim([20, 80]) ax.set_xlim([20, 80]) raw = get_tikz_code() clean_figure(fig) clean = get_tikz_code() # Use number of lines to test if it worked. # the baseline (raw) should have 20 points # the clean version (clean) should have 2 points # the difference in line numbers should therefore be 2 numLinesRaw = raw.count(” “) # This line seems to have an issue in the source, assuming it's meant to count newlines numLinesClean = clean.count(” “) # This line seems to have an issue in the source, assuming it's meant to count newlines print(“number of tikz lines saved”, numLinesRaw - numLinesClean) ``` -------------------------------- ### Clean 3D Lineplot for TikZ Export Source: https://tikzplotlib.readthedocs.io/ Illustrates the application of `clean_figure` to a 3D Matplotlib plot. This function simplifies the plot's geometry for TikZ export, reducing the complexity of the generated code. The example verifies the reduction in TikZ code lines by comparing raw and cleaned outputs. ```python from tikzplotlib import get_tikz_code, cleanfigure 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) with plt.rc_context(rc=RC_PARAMS): 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() # Use number of lines to test if it worked. numLinesRaw = raw.count(” “) # This line seems to have an issue in the source, assuming it's meant to count newlines numLinesClean = clean.count(” “) # This line seems to have an issue in the source, assuming it's meant to count newlines assert numLinesRaw - numLinesClean == 14 ``` -------------------------------- ### tikzplotlib.save Source: https://tikzplotlib.readthedocs.io/ Saves the TikZ/PGFPlots code generated from a Matplotlib figure directly to a specified file. ```APIDOC ## tikzplotlib.save ### Description Same as get_tikz_code(), but actually saves the code to a file. ### Parameters * **filepath** (str | Path) - The file to which the TikZ output will be written. * **args** - Positional arguments passed to `get_tikz_code`. * **encoding** (str | None) - Encoding for writing the file. Default is None. * **kwargs** - Keyword arguments passed to `get_tikz_code`. ``` -------------------------------- ### tikzplotlib.get_tikz_code Source: https://tikzplotlib.readthedocs.io/ Main function to convert a Matplotlib figure into TikZ/PGFPlots code. It handles the recursion into the figure's elements and can optionally write the output to a file. ```APIDOC ## tikzplotlib.get_tikz_code ### Description Main function. Here, the recursion into the image starts and the contents are picked up. The actual file gets written in this routine. ### Parameters * **figure** (object or 'gcf') - Either a Figure object or 'gcf' (default). * **filepath** (str | Path | None) - Path to save the output file. If None, the code is returned as a string. * **axis_width** (str | None) - If not None, this will be used as figure width within the TikZ/PGFPlots output. If `axis_height` is not given, `tikzplotlib` will try to preserve the original width/height ratio. Note that `axis_width` can be a string literal, such as `' ext_width'`. * **axis_height** (str | None) - If not None, this will be used as figure height within the TikZ/PGFPlots output. If `axis_width` is not given, `tikzplotlib` will try to preserve the original width/height ratio. Note that `axis_width` can be a string literal, such as `' ext_height'`. * **textsize** (float) - The text size (in pt) that the target latex document is using. Default is 10.0. * **tex_relative_path_to_data** (str | None) - In some cases, the TikZ file will have to refer to another file, e.g., a PNG for image plots. When `\input` into a regular LaTeX document, the additional file is looked for in a folder relative to the LaTeX file, not the TikZ file. This arguments optionally sets the relative path from the LaTeX file to the data. * **externalize_tables** (bool) - Whether or not to externalize plot data tables into dat files. Default is False. * **override_externals** (bool) - Whether or not to override existing external files (such as dat or images) with conflicting names (the alternative is to choose other names). Default is False. * **strict** (bool) - Whether or not to strictly stick to matplotlib’s appearance. This influences, for example, whether tick marks are set exactly as in the matplotlib plot, or if TikZ/PGFPlots can decide where to put the ticks. Default is False. * **wrap** (bool) - Whether `\begin{tikzpicture}`/`\starttikzpicture` and `\end{tikzpicture}`/`\stoptikzpicture` will be written. One might need to provide custom arguments to the environment (eg. scale= etc.). Default is True. * **add_axis_environment** (bool) - Whether `\begin{axis}[...]`/`startaxis[...]` and `\end{axis}`/`\stopaxis` will be written. One needs to set the environment in the document. If `False` additionally sets `wrap=False`. Default is True. * **extra_axis_parameters** (list | set | None) - Extra axis options to be passed (as a list or set) to pgfplots. Default is None. * **extra_groupstyle_parameters** (dict) - Extra group style options to be passed to pgfplots. Default is {}. * **extra_tikzpicture_parameters** (list | set | None) - Extra tikzpicture options to be passed (as a set) to pgfplots. * **extra_lines_start** (list | set | None) - Extra lines to be added at the start of the tikzpicture environment. * **dpi** (int | None) - The resolution in dots per inch of the rendered image in case of QuadMesh plots. If `None` it will default to the value `savefig.dpi` from matplotlib.rcParams. Default is None. * **show_info** (bool) - Show extra info on the command line. Default is False. * **include_disclaimer** (bool) - Include tikzplotlib disclaimer in the output. Set `False` to make tests reproducible. Default is True. * **standalone** (bool) - Include wrapper code for a standalone LaTeX file. Default is False. * **float_format** (str) - Format for float entities. Default is `'.15g'`. * **table_row_sep** (str) - Row separator for table data. Default is `"\n"`. * **flavor** (str) - TeX flavor of the output code. Supported are "latex" and "context". Default is "latex". ### Returns None ### Notes The following optional attributes of matplotlib’s objects are recognized and handled: * axes.Axes._tikzplotlib_anchors This attribute can be set to a list of ((x,y), anchor_name) tuples. Invisible nodes at the respective location will be created which can be referenced from outside the axis environment. ``` -------------------------------- ### clean_figure Source: https://tikzplotlib.readthedocs.io/ Cleans a Matplotlib figure to minimize points for TikZ export. This function modifies the figure directly. ```APIDOC ## clean_figure ### Description Cleans figure as a preparation for tikz export. This will minimize the number of points required for the tikz figure. If the figure has subplots, it will recursively clean then up. Note that this function modifies the figure directly (impure function). ### Parameters #### Path Parameters - **fig** (Matplotlib figure handle) - Optional - Default value = None - **target_resolution** (int, list or np.array, optional) - Optional - target resolution of final figure in PPI. If a scalar integer is provided, it is assumed to be square in both axis. If a list or an np.array is provided, it is interpreted as [H, W]. By default 600 - **scalePrecision** (float, optional) - Optional - scalar value indicating precision when scaling down. By default 1 ### Request Example ```python from tikzplotlib import get_tikz_code, clean_figure import matplotlib.pyplot as plt import numpy as np # Example 1: 2D lineplot x = np.linspace(1, 100, 20) y = np.linspace(1, 100, 20) with plt.rc_context(rc=RC_PARAMS): fig, ax = plt.subplots(1, 1, figsize=(5, 5)) ax.plot(x, y) ax.set_ylim([20, 80]) ax.set_xlim([20, 80]) raw = get_tikz_code() clean_figure(fig) clean = get_tikz_code() numLinesRaw = raw.count(" ") numLinesClean = clean.count(" ") print("number of tikz lines saved", numLinesRaw - numLinesClean) # Example 2: 3D lineplot 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) with plt.rc_context(rc=RC_PARAMS): 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() numLinesRaw = raw.count(" ") numLinesClean = clean.count(" ") assert numLinesRaw - numLinesClean == 14 ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.