Skip to content

Add figure decorator. #46

@jfear

Description

@jfear
  • lcdblib version: NA
  • Python version: NA
  • Operating System: NA

Description

I have been thinking about streamlining my plotting workflow. I am proposing a decorator to plot functions allow outputting different contexts and formats.

What I Did

My current decorator:

from functools import wraps

def make_figs(fname=None, styles=None, formats=None):
    def _plot_all(func, styles=styles, formats=formats):
        @wraps(func)
        def wrapper(*args, styles=styles, formats=formats, **kwargs):
            def plot_style(style, formats):
                if isinstance(formats, str):
                    formats = [formats]
                elif formats is None:
                    formats = ['png', 'eps']
                
                with plt.style.context('seaborn-' + style):
                    fn = fname + '_' + style
                    func(*args,  **kwargs)
                    plt.tight_layout()
                    if style != 'notebook':
                        for f in formats:
                            plt.savefig('{}.{}'.format(fn, f))
                        plt.close()
                        
            if isinstance(styles, str):
                styles = [styles]
            elif styles is None:
                styles = ['notebook', 'talk', 'poster', 'paper']
                
            for style in styles:
                plot_style(style, formats)

        return wrapper
    return _plot_all

To use you can call it like so:

@make_figs(fname='test_plot', styles=['notebook', 'poster', 'paper'], formats=['png', 'svg'])
def plot(df):
    fig, ax = plt.subplots(1, 1)
    df.plot('X', 'Y', kind='scatter', ax=ax)
    ax.set_title('test')
    return fig

This would then output:

  • test_plot_poster.png
  • test_plot_poster.svg
  • test_plot_paper.png
  • test_plot_paper.svg

The notebook style is displayed.

@daler you probably already have something that does this kind of thing. Just seeing if it is generally useful and should be be added to lcdblib. Or if I should just keep it in my personal library.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions