teeplot


Nameteeplot JSON
Version 1.2.0 PyPI version JSON
download
home_pagehttps://github.com/mmore500/teeplot
Summaryteeplot automatically saves a copy of rendered Jupyter notebook plots
upload_time2024-12-16 04:24:29
maintainerNone
docs_urlNone
authorMatthew Andres Moreno
requires_python>=3.8
licenseMIT license
keywords teeplot
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            .. figure:: docs/assets/teeplot-wordmark.png
   :target: https://github.com/mmore500/teeplot
   :alt: teeplot wordmark


*teeplot* wrangles your data visualizations out of notebooks for you
--------------------------------------------------------------------

|PyPi| |docs| |GitHub stars| |CI| |zenodo|

* Free software: MIT license
* Installation: ``python3 -m pip install teeplot``
* Documentation: https://github.com/mmore500/teeplot/blob/master/README.rst
* Repository: https://github.com/mmore500/teeplot

*teeplot*'s ``tee`` function can wrap your plotting calls to **automatically manage matplotlib file output**, picking meaningful names based on semantic plotting variables.

.. code-block:: python

    # adapted from https://seaborn.pydata.org/generated/seaborn.FacetGrid.html#seaborn.FacetGrid
    import seaborn as sns; from teeplot import teeplot as tp

    tp.tee(sns.lmplot,  # plotter
        sns.load_dataset("tips"), col="time", hue="sex", x="total_bill", y="tip",  # fwded kw/args
        teeplot_postprocess=sns.FacetGrid.add_legend)  # teeplot options

..

    ..

        .. code-block::

            teeplots/col=time+hue=sex+post=add_legend+viz=lmplot+x=total-bill+y=tip+ext=.pdf
            teeplots/col=time+hue=sex+post=add_legend+viz=lmplot+x=total-bill+y=tip+ext=.png

    .. image:: docs/assets/col=time+hue=sex+post=add_legend+viz=lmplot+x=total-bill+y=tip+ext=_padded.png


**Here's how it works:** *teeplot*'s ``tee`` function that acts as a wrapper around your plotting calls.
Give ``tee`` your plotting function (e.g., ``sns.lineplot``) as the first argument and then add the arguments you want to call it with.

*teeplot* automatically captures the function and its arguments, calls the plotter as instructed, and then it handles the matplotlib file output for you.
It generates descriptive filenames for the saved plots by extracting key information from the plot parameters and arguments.
This feature allows you to *keep track of your visualizations easily* by making the process of saving and cataloging your plots more *efficient*, *systematic* and *meaningful*, taking the hassle out of manual file management.

*teeplot* contains several advanced features, such as a ``draftmode`` flag, which will disable file output globally, and the ``teeplot_callback`` kwarg, which delays plot output to allow for figure tweaks.
Read on for details.

Contents
--------

- **Usage** : `Example 1 <#example-1>`_ | `Example 2 <#example-2>`_ | `Example 3 <#example-3>`_ | `Example 4 <#example-4>`_ | `Example 5 <#example-5>`_
- **API** : `teeplot.tee() <#teeplottee>`_ | `Module-Level Configuration <#module-level-configuration>`_ | `Environment Variables <#environment-variables>`_
- **Citing** `here <#citing>`_ | **Credits** `link <#credits>`_

Usage
-----

Example 1
^^^^^^^^^

Simple example demonstrating use with *pandas* built-in plotting.

.. code-block:: python

    # adapted from https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.box.html
    import pandas as pd; from teeplot import teeplot as tp

    age_list = [8, 10, 12, 14, 72, 74, 76, 78, 20, 25, 30, 35, 60, 85]
    df = pd.DataFrame({"gender": list("MMMMMMMMFFFFFF"), "age": age_list})

    tp.tee(df.plot.box,  # plotter...
        column="age", by="gender", figsize=(4, 3))  # ...forwarded kwargs

..

    ..

        .. code-block::

            teeplots/by=gender+column=age+viz=box+ext=.pdf
            teeplots/by=gender+column=age+viz=box+ext=.png

    .. image:: docs/assets/by=gender+column=age+viz=box+ext=_padded.png

----

Example 2
^^^^^^^^^

Example with *seaborn* showing use of ``teed`` context manager interface to allow for plot tweaks before saving.

.. code-block:: python

    # adapted from https://seaborn.pydata.org/examples/horizontal_boxplot.html
    from matplotlib import pyplot as plt
    import seaborn as sns
    from teeplot import teeplot as tp

    with tp.teed(  # plot is finalized upon leaving context
        sns.boxplot,  # plotter...
        sns.load_dataset("planets"),  # ...forwarded arg & kwargs
        x="distance", y="method", hue="method", palette="vlag",
        whis=[0, 100], width=.6,  # ... and then teeplot options
        teeplot_callback=True, teeplot_postprocess="teed.set_xscale('log')"
    ) as ax:
        ax.xaxis.grid(True)  # now some tweaks
        ax.set(ylabel="")
        sns.despine()
        plt.gcf().set_size_inches(10, 4)

..

    ..

        .. code-block::

            teeplots/hue=method+palette=vlag+post=teed-set-xscale-log+viz=boxplot+x=distance+y=method+ext=.pdf
            teeplots/hue=method+palette=vlag+post=teed-set-xscale-log+viz=boxplot+x=distance+y=method+ext=.png

    .. image:: docs/assets/hue=method+palette=vlag+post=teed-set-xscale-log+viz=boxplot+x=distance+y=method+ext=_padded.png

----

Example 3
^^^^^^^^^

Example with matplotlib, showing alternate ``teeplot_callback`` kwarg interface.
We've also used the global configuration option ``save`` to change default output format.

.. code-block:: python

    # adapted from https://matplotlib.org/stable/tutorials/pyplot.html
    from matplotlib import pyplot as plt
    import numpy as np; from teeplot import teeplot as tp
    tp.save = {".eps": True}  # make default output only .eps

    data = {'a': np.arange(50), 'c': np.random.randint(0, 50, 50),
            'd': np.random.randn(50)}
    data['b'], data['d'] = data['a'] + 10 * np.random.randn(50), np.abs(data['d']) * 100

    saveit, __ = tp.tee(  # create a callback object to finalize plot
        plt.scatter,  # plotter...
        data=data, x='a', y='b', c='c', s='d',  # ...forwarded kwargs
        teeplot_callback=True)  # teeplot options
    plt.xlabel('entry a')  # now some tweaks
    plt.ylabel('entry b')
    plt.gcf().set_size_inches(5, 3)
    saveit()  # dispatch output callback

..

    ..

        .. code-block::

            teeplots/c=c+s=d+viz=scatter+x=a+y=b+ext=.eps

    .. image:: docs/assets/c=c+s=d+viz=scatter+x=a+y=b+ext=_padded.png

----

Example 4
^^^^^^^^^

Example with *seaborn* ``FacetGrid`` demonstrating use of ``exec``'ed ``teeplot_postprocess`` that adds a ``map_dataframe`` step over the ``teed`` result value and also results in additional semantic information being added to plot filenames (under the "``post=``" key).

.. code-block:: python

    # adapted from https://seaborn.pydata.org/generated/seaborn.FacetGrid.html#seaborn.FacetGrid
    import seaborn as sns
    from teeplot import teeplot as tp

    tp.tee(
        sns.FacetGrid,  # plotter...
        sns.load_dataset("tips"),  # ...forwarded args & kwwargs
        col="time", hue="sex", aspect=1.5,
        teeplot_postprocess="teed.map_dataframe(sns.scatterplot, x='total_bill', y='tip')")

..

    ..

        .. code-block::

            teeplots/col=time+hue=sex+post=teed-map-dataframe-sns-scatterplot-x-total-bill-y-tip+viz=facetgrid+ext=.pdf
            teeplots/col=time+hue=sex+post=teed-map-dataframe-sns-scatterplot-x-total-bill-y-tip+viz=facetgrid+ext=.png

    .. image:: docs/assets/col=time+hue=sex+post=teed-map-dataframe-sns-scatterplot-x-total-bill-y-tip+viz=facetgrid+ext=_padded.png

----

Example 5
^^^^^^^^^

Demonstration of teeplot use with a custom function.
Note the function name automatically used as "``viz=``" key in output filenames.

.. code-block:: python

    # adapted from https://seaborn.pydata.org/examples/pairgrid_dotplot.html
    import seaborn as sns; from teeplot import teeplot as tp
    df = sns.load_dataset("car_crashes")

    def dot_plot(data, x_vars, y_vars):  # custom plotter
        g = sns.PairGrid(data.sort_values("total", ascending=False),
                        x_vars=x_vars, y_vars=y_vars,
                        height=5, aspect=0.66)
        g.map(sns.stripplot, size=10, orient="h", jitter=False,
            palette="flare_r", linewidth=1, edgecolor="w")
        for ax in g.axes.flat:
            ax.xaxis.grid(False)
            ax.yaxis.grid(True)


    tp.tee(
        dot_plot,  # plotter, then forwarded args/kwargs
        df[df["abbrev"].str.contains("A")], x_vars=df.columns[:-3], y_vars=["abbrev"],
        teeplot_outinclude=["x_vars", "y_vars"], teeplot_save={".eps", ".png"})

..

    ..

        .. code-block::

            teeplots/viz=dot-plot+x-vars=index-total-speeding-alcohol-not-distracted-no-previous-dtype-object+y-vars=abbrev+ext=.eps
            teeplots/viz=dot-plot+x-vars=index-total-speeding-alcohol-not-distracted-no-previous-dtype-object+y-vars=abbrev+ext=.png


    .. image:: docs/assets/viz=dot-plot+x-vars=index-total-speeding-alcohol-not-distracted-no-previous-dtype-object+y-vars=abbrev+ext=_padded.png

----

Further Examples
^^^^^^^^^^^^^^^^

Find more examples and use cases `on medium <https://medium.com/towards-data-science/an-easier-way-to-wrangle-jupyter-notebook-visualizations-620a86cd9279>`_.


API
---

``teeplot.tee()``
^^^^^^^^^^^^^^^^^

Executes a plotting function and saves the resulting plot to specified formats using a descriptive filename automatically generated from plotting function arguments.


+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Parameter                  | Description                                                                                                                                                                                                                              |
+============================+==========================================================================================================================================================================================================================================+
| ``plotter``                | The plotting function to be executed. *Required.*                                                                                                                                                                                        |
+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| *Additional args & kwargs* | Forwarded to the plotting function and used to build the output filename.                                                                                                                                                                |
+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``teeplot_callback``       | If True, returns a tuple with a callback to dispatch plot save instead of immediately saving the plot after running the plotter. Default is False.                                                                                       |
+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``teeplot_dpi``            | Resolution for rasterized components of saved plots, default is publication-quality 300 dpi.                                                                                                                                             |
+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``teeplot_oncollision``    | Strategy for handling filename collisions: "error", "fix", "ignore", or "warn", default "warn"; inferred from environment if not specified.                                                                                              |
+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``teeplot_outattrs``       | Dict with additional key-value attributes to include in the output filename.                                                                                                                                                             |
+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``teeplot_outdir``         | Base directory for saving plots, default "teeplots".                                                                                                                                                                                     |
+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``teeplot_outinclude``     | Attribute keys to always include, if present, in the output filename.                                                                                                                                                                    |
+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``teeplot_outexclude``     | Attribute keys to always exclude, if present, from the output filename.                                                                                                                                                                  |
+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``teeplot_postprocess``    | Actions to perform after plotting but before saving. Can be a string of code to ``exec`` or a callable function. If a string, it's executed with access to ``plt`` and ``sns`` (if installed), and the plotter return value as ``teed``. |
+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``teeplot_save``           | File formats to save the plots in. Defaults to global settings if ``True``, all output suppressed if ``False``. Default global setting is ``{" .png", ".pdf"}``. Supported: ".eps", ".png", ".pdf", ".ps", ".svg".                       |
+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``teeplot_show``           | Dictates whether ``plt.show()`` should be called after plot is saved. If True, the plot is displayed using ``plt.show()``. Default behavior is to display if an interactive environment is detected (e.g., a notebook).                  |
+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``teeplot_subdir``         | Optionally, subdirectory within the main output directory for plot organization.                                                                                                                                                         |
+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``teeplot_transparent``    | Option to save the plot with a transparent background, default True.                                                                                                                                                                     |
+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| ``teeplot_verbose``        | Toggles printing of saved filenames, default True.                                                                                                                                                                                       |
+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

**Return Value**: returned result from plotter call if ``teeplot_callback`` is ``False``, otherwise tuple of save-plot callback and result from plotter call.


Module-Level Configuration
^^^^^^^^^^^^^^^^^^^^^^^^^^

-  ``teeplot.draftmode``: A boolean indicating whether to suppress output to all file formats.
-  ``teeplot.oncollision``: Default strategy for handling filename collisions, options are 'error', 'fix', 'ignore', or 'warn'.
-  ``teeplot.save``: A dictionary mapping file formats (e.g., ".png") to default save behavior as ``True`` (always output), ``False`` (never output), or ``None`` (defer to call kwargs).

Environment Variables
^^^^^^^^^^^^^^^^^^^^^

-  ``TEEPLOT_ONCOLLISION``: Configures the default collision handling strategy. See ``teeplot_oncollision`` kwarg
-  ``TEEPLOT_DRAFTMODE``: If set, enables draft mode globally.
-  ``TEEPLOT_<FORMAT>``: Boolean flags that determine default behavior for each format (e.g., ``EPS``, ``PNG``, ``PDF``, ``PS``, ``SVG``); "defer" defers to call kwargs.

Citing
------

If *teeplot* contributes to a scholarly publication, please cite it as

    Matthew Andres Moreno. (2023). mmore500/teeplot. Zenodo. https://doi.org/10.5281/zenodo.10440670

.. code:: bibtex

    @software{moreno2023teeplot,
      author = {Matthew Andres Moreno},
      title = {mmore500/teeplot},
      month = dec,
      year = 2023,
      publisher = {Zenodo},
      doi = {10.5281/zenodo.10440670},
      url = {https://doi.org/10.5281/zenodo.10440670}
    }

And don't forget to leave a `star on GitHub <https://github.com/mmore500/teeplot/stargazers>`__!

Credits
-------

Output filenames are constructed using the `keyname <https://github.com/mmore500/keyname>`_ package.

This package was created with Cookiecutter_ and the `audreyr/cookiecutter-pypackage`_ project template.

.. _Cookiecutter: https://github.com/audreyr/cookiecutter
.. _`audreyr/cookiecutter-pypackage`: https://github.com/audreyr/cookiecutter-pypackage

.. |PyPi| image:: https://img.shields.io/pypi/v/teeplot.svg
   :target: https://pypi.python.org/pypi/teeplot
.. |CI| image:: https://github.com/mmore500/teeplot/actions/workflows/CI.yml/badge.svg
   :target: https://github.com/mmore500/teeplot/actions
.. |GitHub stars| image:: https://img.shields.io/github/stars/mmore500/teeplot.svg?style=round-square&logo=github&label=Stars&logoColor=white
   :target: https://github.com/mmore500/teeplot
.. |docs| image:: https://img.shields.io/badge/docs%20-%20readme%20-%20fedcba?logo=github
   :target: https://github.com/mmore500/teeplot/blob/master/README.rst
.. |zenodo| image:: https://zenodo.org/badge/DOI/10.5281/zenodo.10440670.svg
   :target: https://doi.org/10.5281/zenodo.10440670



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/mmore500/teeplot",
    "name": "teeplot",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "teeplot",
    "author": "Matthew Andres Moreno",
    "author_email": "m.more500@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/1f/13/db59fe73890e169515cc104f3f2f96a614fa55562fa03eace795e22a38c8/teeplot-1.2.0.tar.gz",
    "platform": null,
    "description": ".. figure:: docs/assets/teeplot-wordmark.png\n   :target: https://github.com/mmore500/teeplot\n   :alt: teeplot wordmark\n\n\n*teeplot* wrangles your data visualizations out of notebooks for you\n--------------------------------------------------------------------\n\n|PyPi| |docs| |GitHub stars| |CI| |zenodo|\n\n* Free software: MIT license\n* Installation: ``python3 -m pip install teeplot``\n* Documentation: https://github.com/mmore500/teeplot/blob/master/README.rst\n* Repository: https://github.com/mmore500/teeplot\n\n*teeplot*'s ``tee`` function can wrap your plotting calls to **automatically manage matplotlib file output**, picking meaningful names based on semantic plotting variables.\n\n.. code-block:: python\n\n    # adapted from https://seaborn.pydata.org/generated/seaborn.FacetGrid.html#seaborn.FacetGrid\n    import seaborn as sns; from teeplot import teeplot as tp\n\n    tp.tee(sns.lmplot,  # plotter\n        sns.load_dataset(\"tips\"), col=\"time\", hue=\"sex\", x=\"total_bill\", y=\"tip\",  # fwded kw/args\n        teeplot_postprocess=sns.FacetGrid.add_legend)  # teeplot options\n\n..\n\n    ..\n\n        .. code-block::\n\n            teeplots/col=time+hue=sex+post=add_legend+viz=lmplot+x=total-bill+y=tip+ext=.pdf\n            teeplots/col=time+hue=sex+post=add_legend+viz=lmplot+x=total-bill+y=tip+ext=.png\n\n    .. image:: docs/assets/col=time+hue=sex+post=add_legend+viz=lmplot+x=total-bill+y=tip+ext=_padded.png\n\n\n**Here's how it works:** *teeplot*'s ``tee`` function that acts as a wrapper around your plotting calls.\nGive ``tee`` your plotting function (e.g., ``sns.lineplot``) as the first argument and then add the arguments you want to call it with.\n\n*teeplot* automatically captures the function and its arguments, calls the plotter as instructed, and then it handles the matplotlib file output for you.\nIt generates descriptive filenames for the saved plots by extracting key information from the plot parameters and arguments.\nThis feature allows you to *keep track of your visualizations easily* by making the process of saving and cataloging your plots more *efficient*, *systematic* and *meaningful*, taking the hassle out of manual file management.\n\n*teeplot* contains several advanced features, such as a ``draftmode`` flag, which will disable file output globally, and the ``teeplot_callback`` kwarg, which delays plot output to allow for figure tweaks.\nRead on for details.\n\nContents\n--------\n\n- **Usage** : `Example 1 <#example-1>`_ | `Example 2 <#example-2>`_ | `Example 3 <#example-3>`_ | `Example 4 <#example-4>`_ | `Example 5 <#example-5>`_\n- **API** : `teeplot.tee() <#teeplottee>`_ | `Module-Level Configuration <#module-level-configuration>`_ | `Environment Variables <#environment-variables>`_\n- **Citing** `here <#citing>`_ | **Credits** `link <#credits>`_\n\nUsage\n-----\n\nExample 1\n^^^^^^^^^\n\nSimple example demonstrating use with *pandas* built-in plotting.\n\n.. code-block:: python\n\n    # adapted from https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.box.html\n    import pandas as pd; from teeplot import teeplot as tp\n\n    age_list = [8, 10, 12, 14, 72, 74, 76, 78, 20, 25, 30, 35, 60, 85]\n    df = pd.DataFrame({\"gender\": list(\"MMMMMMMMFFFFFF\"), \"age\": age_list})\n\n    tp.tee(df.plot.box,  # plotter...\n        column=\"age\", by=\"gender\", figsize=(4, 3))  # ...forwarded kwargs\n\n..\n\n    ..\n\n        .. code-block::\n\n            teeplots/by=gender+column=age+viz=box+ext=.pdf\n            teeplots/by=gender+column=age+viz=box+ext=.png\n\n    .. image:: docs/assets/by=gender+column=age+viz=box+ext=_padded.png\n\n----\n\nExample 2\n^^^^^^^^^\n\nExample with *seaborn* showing use of ``teed`` context manager interface to allow for plot tweaks before saving.\n\n.. code-block:: python\n\n    # adapted from https://seaborn.pydata.org/examples/horizontal_boxplot.html\n    from matplotlib import pyplot as plt\n    import seaborn as sns\n    from teeplot import teeplot as tp\n\n    with tp.teed(  # plot is finalized upon leaving context\n        sns.boxplot,  # plotter...\n        sns.load_dataset(\"planets\"),  # ...forwarded arg & kwargs\n        x=\"distance\", y=\"method\", hue=\"method\", palette=\"vlag\",\n        whis=[0, 100], width=.6,  # ... and then teeplot options\n        teeplot_callback=True, teeplot_postprocess=\"teed.set_xscale('log')\"\n    ) as ax:\n        ax.xaxis.grid(True)  # now some tweaks\n        ax.set(ylabel=\"\")\n        sns.despine()\n        plt.gcf().set_size_inches(10, 4)\n\n..\n\n    ..\n\n        .. code-block::\n\n            teeplots/hue=method+palette=vlag+post=teed-set-xscale-log+viz=boxplot+x=distance+y=method+ext=.pdf\n            teeplots/hue=method+palette=vlag+post=teed-set-xscale-log+viz=boxplot+x=distance+y=method+ext=.png\n\n    .. image:: docs/assets/hue=method+palette=vlag+post=teed-set-xscale-log+viz=boxplot+x=distance+y=method+ext=_padded.png\n\n----\n\nExample 3\n^^^^^^^^^\n\nExample with matplotlib, showing alternate ``teeplot_callback`` kwarg interface.\nWe've also used the global configuration option ``save`` to change default output format.\n\n.. code-block:: python\n\n    # adapted from https://matplotlib.org/stable/tutorials/pyplot.html\n    from matplotlib import pyplot as plt\n    import numpy as np; from teeplot import teeplot as tp\n    tp.save = {\".eps\": True}  # make default output only .eps\n\n    data = {'a': np.arange(50), 'c': np.random.randint(0, 50, 50),\n            'd': np.random.randn(50)}\n    data['b'], data['d'] = data['a'] + 10 * np.random.randn(50), np.abs(data['d']) * 100\n\n    saveit, __ = tp.tee(  # create a callback object to finalize plot\n        plt.scatter,  # plotter...\n        data=data, x='a', y='b', c='c', s='d',  # ...forwarded kwargs\n        teeplot_callback=True)  # teeplot options\n    plt.xlabel('entry a')  # now some tweaks\n    plt.ylabel('entry b')\n    plt.gcf().set_size_inches(5, 3)\n    saveit()  # dispatch output callback\n\n..\n\n    ..\n\n        .. code-block::\n\n            teeplots/c=c+s=d+viz=scatter+x=a+y=b+ext=.eps\n\n    .. image:: docs/assets/c=c+s=d+viz=scatter+x=a+y=b+ext=_padded.png\n\n----\n\nExample 4\n^^^^^^^^^\n\nExample with *seaborn* ``FacetGrid`` demonstrating use of ``exec``'ed ``teeplot_postprocess`` that adds a ``map_dataframe`` step over the ``teed`` result value and also results in additional semantic information being added to plot filenames (under the \"``post=``\" key).\n\n.. code-block:: python\n\n    # adapted from https://seaborn.pydata.org/generated/seaborn.FacetGrid.html#seaborn.FacetGrid\n    import seaborn as sns\n    from teeplot import teeplot as tp\n\n    tp.tee(\n        sns.FacetGrid,  # plotter...\n        sns.load_dataset(\"tips\"),  # ...forwarded args & kwwargs\n        col=\"time\", hue=\"sex\", aspect=1.5,\n        teeplot_postprocess=\"teed.map_dataframe(sns.scatterplot, x='total_bill', y='tip')\")\n\n..\n\n    ..\n\n        .. code-block::\n\n            teeplots/col=time+hue=sex+post=teed-map-dataframe-sns-scatterplot-x-total-bill-y-tip+viz=facetgrid+ext=.pdf\n            teeplots/col=time+hue=sex+post=teed-map-dataframe-sns-scatterplot-x-total-bill-y-tip+viz=facetgrid+ext=.png\n\n    .. image:: docs/assets/col=time+hue=sex+post=teed-map-dataframe-sns-scatterplot-x-total-bill-y-tip+viz=facetgrid+ext=_padded.png\n\n----\n\nExample 5\n^^^^^^^^^\n\nDemonstration of teeplot use with a custom function.\nNote the function name automatically used as \"``viz=``\" key in output filenames.\n\n.. code-block:: python\n\n    # adapted from https://seaborn.pydata.org/examples/pairgrid_dotplot.html\n    import seaborn as sns; from teeplot import teeplot as tp\n    df = sns.load_dataset(\"car_crashes\")\n\n    def dot_plot(data, x_vars, y_vars):  # custom plotter\n        g = sns.PairGrid(data.sort_values(\"total\", ascending=False),\n                        x_vars=x_vars, y_vars=y_vars,\n                        height=5, aspect=0.66)\n        g.map(sns.stripplot, size=10, orient=\"h\", jitter=False,\n            palette=\"flare_r\", linewidth=1, edgecolor=\"w\")\n        for ax in g.axes.flat:\n            ax.xaxis.grid(False)\n            ax.yaxis.grid(True)\n\n\n    tp.tee(\n        dot_plot,  # plotter, then forwarded args/kwargs\n        df[df[\"abbrev\"].str.contains(\"A\")], x_vars=df.columns[:-3], y_vars=[\"abbrev\"],\n        teeplot_outinclude=[\"x_vars\", \"y_vars\"], teeplot_save={\".eps\", \".png\"})\n\n..\n\n    ..\n\n        .. code-block::\n\n            teeplots/viz=dot-plot+x-vars=index-total-speeding-alcohol-not-distracted-no-previous-dtype-object+y-vars=abbrev+ext=.eps\n            teeplots/viz=dot-plot+x-vars=index-total-speeding-alcohol-not-distracted-no-previous-dtype-object+y-vars=abbrev+ext=.png\n\n\n    .. image:: docs/assets/viz=dot-plot+x-vars=index-total-speeding-alcohol-not-distracted-no-previous-dtype-object+y-vars=abbrev+ext=_padded.png\n\n----\n\nFurther Examples\n^^^^^^^^^^^^^^^^\n\nFind more examples and use cases `on medium <https://medium.com/towards-data-science/an-easier-way-to-wrangle-jupyter-notebook-visualizations-620a86cd9279>`_.\n\n\nAPI\n---\n\n``teeplot.tee()``\n^^^^^^^^^^^^^^^^^\n\nExecutes a plotting function and saves the resulting plot to specified formats using a descriptive filename automatically generated from plotting function arguments.\n\n\n+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| Parameter                  | Description                                                                                                                                                                                                                              |\n+============================+==========================================================================================================================================================================================================================================+\n| ``plotter``                | The plotting function to be executed. *Required.*                                                                                                                                                                                        |\n+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| *Additional args & kwargs* | Forwarded to the plotting function and used to build the output filename.                                                                                                                                                                |\n+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| ``teeplot_callback``       | If True, returns a tuple with a callback to dispatch plot save instead of immediately saving the plot after running the plotter. Default is False.                                                                                       |\n+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| ``teeplot_dpi``            | Resolution for rasterized components of saved plots, default is publication-quality 300 dpi.                                                                                                                                             |\n+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| ``teeplot_oncollision``    | Strategy for handling filename collisions: \"error\", \"fix\", \"ignore\", or \"warn\", default \"warn\"; inferred from environment if not specified.                                                                                              |\n+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| ``teeplot_outattrs``       | Dict with additional key-value attributes to include in the output filename.                                                                                                                                                             |\n+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| ``teeplot_outdir``         | Base directory for saving plots, default \"teeplots\".                                                                                                                                                                                     |\n+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| ``teeplot_outinclude``     | Attribute keys to always include, if present, in the output filename.                                                                                                                                                                    |\n+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| ``teeplot_outexclude``     | Attribute keys to always exclude, if present, from the output filename.                                                                                                                                                                  |\n+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| ``teeplot_postprocess``    | Actions to perform after plotting but before saving. Can be a string of code to ``exec`` or a callable function. If a string, it's executed with access to ``plt`` and ``sns`` (if installed), and the plotter return value as ``teed``. |\n+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| ``teeplot_save``           | File formats to save the plots in. Defaults to global settings if ``True``, all output suppressed if ``False``. Default global setting is ``{\" .png\", \".pdf\"}``. Supported: \".eps\", \".png\", \".pdf\", \".ps\", \".svg\".                       |\n+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| ``teeplot_show``           | Dictates whether ``plt.show()`` should be called after plot is saved. If True, the plot is displayed using ``plt.show()``. Default behavior is to display if an interactive environment is detected (e.g., a notebook).                  |\n+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| ``teeplot_subdir``         | Optionally, subdirectory within the main output directory for plot organization.                                                                                                                                                         |\n+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| ``teeplot_transparent``    | Option to save the plot with a transparent background, default True.                                                                                                                                                                     |\n+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| ``teeplot_verbose``        | Toggles printing of saved filenames, default True.                                                                                                                                                                                       |\n+----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n\n**Return Value**: returned result from plotter call if ``teeplot_callback`` is ``False``, otherwise tuple of save-plot callback and result from plotter call.\n\n\nModule-Level Configuration\n^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n-  ``teeplot.draftmode``: A boolean indicating whether to suppress output to all file formats.\n-  ``teeplot.oncollision``: Default strategy for handling filename collisions, options are 'error', 'fix', 'ignore', or 'warn'.\n-  ``teeplot.save``: A dictionary mapping file formats (e.g., \".png\") to default save behavior as ``True`` (always output), ``False`` (never output), or ``None`` (defer to call kwargs).\n\nEnvironment Variables\n^^^^^^^^^^^^^^^^^^^^^\n\n-  ``TEEPLOT_ONCOLLISION``: Configures the default collision handling strategy. See ``teeplot_oncollision`` kwarg\n-  ``TEEPLOT_DRAFTMODE``: If set, enables draft mode globally.\n-  ``TEEPLOT_<FORMAT>``: Boolean flags that determine default behavior for each format (e.g., ``EPS``, ``PNG``, ``PDF``, ``PS``, ``SVG``); \"defer\" defers to call kwargs.\n\nCiting\n------\n\nIf *teeplot* contributes to a scholarly publication, please cite it as\n\n    Matthew Andres Moreno. (2023). mmore500/teeplot. Zenodo. https://doi.org/10.5281/zenodo.10440670\n\n.. code:: bibtex\n\n    @software{moreno2023teeplot,\n      author = {Matthew Andres Moreno},\n      title = {mmore500/teeplot},\n      month = dec,\n      year = 2023,\n      publisher = {Zenodo},\n      doi = {10.5281/zenodo.10440670},\n      url = {https://doi.org/10.5281/zenodo.10440670}\n    }\n\nAnd don't forget to leave a `star on GitHub <https://github.com/mmore500/teeplot/stargazers>`__!\n\nCredits\n-------\n\nOutput filenames are constructed using the `keyname <https://github.com/mmore500/keyname>`_ package.\n\nThis package was created with Cookiecutter_ and the `audreyr/cookiecutter-pypackage`_ project template.\n\n.. _Cookiecutter: https://github.com/audreyr/cookiecutter\n.. _`audreyr/cookiecutter-pypackage`: https://github.com/audreyr/cookiecutter-pypackage\n\n.. |PyPi| image:: https://img.shields.io/pypi/v/teeplot.svg\n   :target: https://pypi.python.org/pypi/teeplot\n.. |CI| image:: https://github.com/mmore500/teeplot/actions/workflows/CI.yml/badge.svg\n   :target: https://github.com/mmore500/teeplot/actions\n.. |GitHub stars| image:: https://img.shields.io/github/stars/mmore500/teeplot.svg?style=round-square&logo=github&label=Stars&logoColor=white\n   :target: https://github.com/mmore500/teeplot\n.. |docs| image:: https://img.shields.io/badge/docs%20-%20readme%20-%20fedcba?logo=github\n   :target: https://github.com/mmore500/teeplot/blob/master/README.rst\n.. |zenodo| image:: https://zenodo.org/badge/DOI/10.5281/zenodo.10440670.svg\n   :target: https://doi.org/10.5281/zenodo.10440670\n\n\n",
    "bugtrack_url": null,
    "license": "MIT license",
    "summary": "teeplot automatically saves a copy of rendered Jupyter notebook plots",
    "version": "1.2.0",
    "project_urls": {
        "Homepage": "https://github.com/mmore500/teeplot"
    },
    "split_keywords": [
        "teeplot"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "59e3da3dbde5945fdba13089da3dce399e8609a1e0290752fc8aafe3ba252440",
                "md5": "93d893e07457b0d2e38e5f9c17686233",
                "sha256": "3b11d4dad1424ba716121b228b7781ed56eeda2f351f114ec48a9c80d71632ef"
            },
            "downloads": -1,
            "filename": "teeplot-1.2.0-py2.py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "93d893e07457b0d2e38e5f9c17686233",
            "packagetype": "bdist_wheel",
            "python_version": "py2.py3",
            "requires_python": ">=3.8",
            "size": 11719,
            "upload_time": "2024-12-16T04:24:27",
            "upload_time_iso_8601": "2024-12-16T04:24:27.556548Z",
            "url": "https://files.pythonhosted.org/packages/59/e3/da3dbde5945fdba13089da3dce399e8609a1e0290752fc8aafe3ba252440/teeplot-1.2.0-py2.py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "1f13db59fe73890e169515cc104f3f2f96a614fa55562fa03eace795e22a38c8",
                "md5": "4feb8a116096be2b7589e4224c157be7",
                "sha256": "93bf56cf4367810a4f9046776b10d326ca978aa5eda6669e0a33eb1899497d38"
            },
            "downloads": -1,
            "filename": "teeplot-1.2.0.tar.gz",
            "has_sig": false,
            "md5_digest": "4feb8a116096be2b7589e4224c157be7",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 1507704,
            "upload_time": "2024-12-16T04:24:29",
            "upload_time_iso_8601": "2024-12-16T04:24:29.900152Z",
            "url": "https://files.pythonhosted.org/packages/1f/13/db59fe73890e169515cc104f3f2f96a614fa55562fa03eace795e22a38c8/teeplot-1.2.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-12-16 04:24:29",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "mmore500",
    "github_project": "teeplot",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "tox": true,
    "lcname": "teeplot"
}
        
Elapsed time: 2.99583s