jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def finalize(legend, apply_return_val):
    if apply_return_val:
        if legend != None:
            f = legend.get_frame()
            f.set_facecolor('white')
            f.set_alpha(1)

        sns.despine(offset=5)

        ax = plt.gca()
        ax.yaxis.grid(True)
        for line in ax.get_ygridlines():
            line.set_linewidth(0.5)
//  [python]
def finalize(legend, apply_return_val):
    if apply_return_val:
        if legend != None:
            f = legend.get_frame()
            f.set_facecolor('white')
            f.set_alpha(1)

        sns.utils.despine(offset=5)

        ax = plt.gca()
        ax.yaxis.grid(True)
        for line in ax.get_ygridlines():
            line.set_linewidth(0.5)
//  [python]
def plot_correlations(correlation_sets, x_key, y_key,
                      x_label=None, y_label=None, name=None):

    figure_name = saving.build_figure_name("correlations", name)

    if not isinstance(correlation_sets, dict):
        correlation_sets = {"correlations": correlation_sets}

    figure = pyplot.figure()
    axis = figure.add_subplot(1, 1, 1)
    seaborn.despine()

    axis.set_xlabel(x_label)
    axis.set_ylabel(y_label)

    for correlation_set_name, correlation_set in correlation_sets.items():
        axis.scatter(
            correlation_set[x_key], correlation_set[y_key],
            label=correlation_set_name
        )

    if len(correlation_sets) > 1:
        axis.legend(loc="best")

    return figure, figure_name
//  [python]
def plot_correlations(correlation_sets, x_key, y_key,
                      x_label=None, y_label=None, name=None):

    figure_name = saving.build_figure_name("correlations", name)

    if not isinstance(correlation_sets, dict):
        correlation_sets = {"correlations": correlation_sets}

    figure = pyplot.figure()
    axis = figure.add_subplot(1, 1, 1)
    seaborn.utils.despine()

    axis.set_xlabel(x_label)
    axis.set_ylabel(y_label)

    for correlation_set_name, correlation_set in correlation_sets.items():
        axis.scatter(
            correlation_set[x_key], correlation_set[y_key],
            label=correlation_set_name
        )

    if len(correlation_sets) > 1:
        axis.legend(loc="best")

    return figure, figure_name
//  [python]
def scatter(data, x, y, hue, palette, fig_size, despine={}, add_args={}, ax_args={}):
    # https://seaborn.pydata.org/generated/seaborn.scatterplot.html#seaborn.scatterplot

    args = clean_args(locals())

    g = sns.scatterplot(**args, **add_args)
    g.set(**ax_args)

    if fig_size:
        set_fig_size(g, fig_size)

    if despine:
        sns.despine(**despine)

    # tight layout
    plt.tight_layout()

    return base64img()
//  [python]
def scatter(data, x, y, hue, palette, fig_size, despine={}, add_args={}, ax_args={}):
    # https://seaborn.pydata.org/generated/seaborn.scatterplot.html#seaborn.scatterplot

    args = clean_args(locals())

    g = sns.scatterplot(**args, **add_args)
    g.set(**ax_args)

    if fig_size:
        set_fig_size(g, fig_size)

    if despine:
        sns.utils.despine(**despine)

    # tight layout
    plt.tight_layout()

    return base64img()
//  [python]
def rel(
    data,
    x,
    y,
    hue,
    size,
    style,
    row,
    col,
    col_wrap,
    kind="scatter",
    palette="deep",
    fig_size="",
    despine={},
    add_args={},
    ax_args={},
):
    # https://seaborn.pydata.org/generated/seaborn.relplot.html#seaborn.relplot

    args = clean_args(locals())

    g = sns.relplot(**args, **add_args)
    g.set(**ax_args)

    if fig_size:
        set_fig_size(g, fig_size)

    if despine:
        sns.despine(**despine)

    # tight layout
    plt.tight_layout()

    return base64img()
//  [python]
def rel(
    data,
    x,
    y,
    hue,
    size,
    style,
    row,
    col,
    col_wrap,
    kind="scatter",
    palette="deep",
    fig_size="",
    despine={},
    add_args={},
    ax_args={},
):
    # https://seaborn.pydata.org/generated/seaborn.relplot.html#seaborn.relplot

    args = clean_args(locals())

    g = sns.relplot(**args, **add_args)
    g.set(**ax_args)

    if fig_size:
        set_fig_size(g, fig_size)

    if despine:
        sns.utils.despine(**despine)

    # tight layout
    plt.tight_layout()

    return base64img()
//  [python]
def dis(
    data, x, y, hue, row, col, col_wrap, kind, rug, legend, palette, fig_size, despine={}, add_args={}, ax_args={}
):

    # https://seaborn.pydata.org/generated/seaborn.displot.html#seaborn.displot

    args = clean_args(locals())

    g = sns.displot(**args, **add_args)
    g.set(**ax_args)

    if fig_size:
        set_fig_size(g, fig_size)

    if despine:
        sns.despine(**despine)

    # tight layout
    plt.tight_layout()

    return base64img()
//  [python]
def dis(
    data, x, y, hue, row, col, col_wrap, kind, rug, legend, palette, fig_size, despine={}, add_args={}, ax_args={}
):

    # https://seaborn.pydata.org/generated/seaborn.displot.html#seaborn.displot

    args = clean_args(locals())

    g = sns.displot(**args, **add_args)
    g.set(**ax_args)

    if fig_size:
        set_fig_size(g, fig_size)

    if despine:
        sns.utils.despine(**despine)

    # tight layout
    plt.tight_layout()

    return base64img()
//  [python]
def hist(
    data,
    x,
    y,
    hue,
    stat,
    cumulative,
    multiple,
    element,
    fill,
    shrink,
    kde,
    legend,
    palette,
    fig_size,
    despine={},
    add_args={},
    ax_args={},
):
    # https://seaborn.pydata.org/generated/seaborn.histplot.html#seaborn.histplot

    args = clean_args(locals())

    g = sns.histplot(**args, **add_args)
    g.set(**ax_args)

    if fig_size:
        set_fig_size(g, fig_size)

    if despine:
        sns.despine(**despine)

    # tight layout
    plt.tight_layout()

    return base64img()
//  [python]
def hist(
    data,
    x,
    y,
    hue,
    stat,
    cumulative,
    multiple,
    element,
    fill,
    shrink,
    kde,
    legend,
    palette,
    fig_size,
    despine={},
    add_args={},
    ax_args={},
):
    # https://seaborn.pydata.org/generated/seaborn.histplot.html#seaborn.histplot

    args = clean_args(locals())

    g = sns.histplot(**args, **add_args)
    g.set(**ax_args)

    if fig_size:
        set_fig_size(g, fig_size)

    if despine:
        sns.utils.despine(**despine)

    # tight layout
    plt.tight_layout()

    return base64img()
//  [python]
def strip(data, x, y, hue, jitter, size, palette, fig_size, despine={}, add_args={}, ax_args={}):
    # https://seaborn.pydata.org/generated/seaborn.stripplot.html#seaborn.stripplot

    args = clean_args(locals())

    g = sns.stripplot(**args, **add_args)
    g.set(**ax_args)

    if fig_size:
        set_fig_size(g, fig_size)

    if despine:
        sns.despine(**despine)

    # tight layout
    plt.tight_layout()

    return base64img()
//  [python]
def strip(data, x, y, hue, jitter, size, palette, fig_size, despine={}, add_args={}, ax_args={}):
    # https://seaborn.pydata.org/generated/seaborn.stripplot.html#seaborn.stripplot

    args = clean_args(locals())

    g = sns.stripplot(**args, **add_args)
    g.set(**ax_args)

    if fig_size:
        set_fig_size(g, fig_size)

    if despine:
        sns.utils.despine(**despine)

    # tight layout
    plt.tight_layout()

    return base64img()
//  [python]
def kde(
    data,
    x,
    y,
    hue,
    cut,
    cumulative,
    multiple,
    common_norm,
    common_grid,
    levels,
    thresh,
    alpha,
    fill,
    legend,
    palette,
    fig_size,
    despine={},
    add_args={},
    ax_args={},
):
    # https://seaborn.pydata.org/generated/seaborn.kdeplot.html#seaborn.kdeplot

    args = clean_args(locals())

    g = sns.kdeplot(**args, **add_args)
    g.set(**ax_args)

    if fig_size:
        set_fig_size(g, fig_size)

    if despine:
        sns.despine(**despine)

    # tight layout
    plt.tight_layout()

    return base64img()
//  [python]
def kde(
    data,
    x,
    y,
    hue,
    cut,
    cumulative,
    multiple,
    common_norm,
    common_grid,
    levels,
    thresh,
    alpha,
    fill,
    legend,
    palette,
    fig_size,
    despine={},
    add_args={},
    ax_args={},
):
    # https://seaborn.pydata.org/generated/seaborn.kdeplot.html#seaborn.kdeplot

    args = clean_args(locals())

    g = sns.kdeplot(**args, **add_args)
    g.set(**ax_args)

    if fig_size:
        set_fig_size(g, fig_size)

    if despine:
        sns.utils.despine(**despine)

    # tight layout
    plt.tight_layout()

    return base64img()
//  [python]
def swarm(data, x, y, hue, dodge, size, palette, fig_size, despine={}, add_args={}, ax_args={}):
    # https://seaborn.pydata.org/generated/seaborn.swarmplot.html#seaborn.swarmplot

    args = clean_args(locals())

    g = sns.swarmplot(**args, **add_args)
    g.set(**ax_args)

    if fig_size:
        set_fig_size(g, fig_size)

    if despine:
        sns.despine(**despine)

    # tight layout
    plt.tight_layout()

    return base64img()
//  [python]
def swarm(data, x, y, hue, dodge, size, palette, fig_size, despine={}, add_args={}, ax_args={}):
    # https://seaborn.pydata.org/generated/seaborn.swarmplot.html#seaborn.swarmplot

    args = clean_args(locals())

    g = sns.swarmplot(**args, **add_args)
    g.set(**ax_args)

    if fig_size:
        set_fig_size(g, fig_size)

    if despine:
        sns.utils.despine(**despine)

    # tight layout
    plt.tight_layout()

    return base64img()
//  [python]
def box(data, x, y, hue, palette, fig_size, despine={}, add_args={}, ax_args={}):
    # https://seaborn.pydata.org/generated/seaborn.boxplot.html#seaborn.boxplot
    # get all local arguments and check if = ''

    args = clean_args(locals())

    g = sns.boxplot(**args, **add_args)
    g.set(**ax_args)

    if fig_size:
        set_fig_size(g, fig_size)

    if despine:
        sns.despine(**despine)

    # tight layout
    plt.tight_layout()

    return base64img()
//  [python]
def box(data, x, y, hue, palette, fig_size, despine={}, add_args={}, ax_args={}):
    # https://seaborn.pydata.org/generated/seaborn.boxplot.html#seaborn.boxplot
    # get all local arguments and check if = ''

    args = clean_args(locals())

    g = sns.boxplot(**args, **add_args)
    g.set(**ax_args)

    if fig_size:
        set_fig_size(g, fig_size)

    if despine:
        sns.utils.despine(**despine)

    # tight layout
    plt.tight_layout()

    return base64img()
//  [python]
def __init__(self, stream, fig, axes, window, scale, dejitter=True):
        """Init"""
        self.stream = stream
        self.window = window
        self.scale = scale
        self.dejitter = dejitter
        self.inlet = StreamInlet(stream, max_chunklen=LSL_EEG_CHUNK)
        self.filt = True
        self.subsample = VIEW_SUBSAMPLE

        info = self.inlet.info()
        description = info.desc()

        self.sfreq = info.nominal_srate()
        self.n_samples = int(self.sfreq * self.window)
        self.n_chan = info.channel_count()

        ch = description.child('channels').first_child()
        ch_names = [ch.child_value('label')]

        for i in range(self.n_chan):
            ch = ch.next_sibling()
            ch_names.append(ch.child_value('label'))

        self.ch_names = ch_names

        fig.canvas.mpl_connect('key_press_event', self.OnKeypress)
        fig.canvas.mpl_connect('button_press_event', self.onclick)

        self.fig = fig
        self.axes = axes

        sns.despine(left=True)

        self.data = np.zeros((self.n_samples, self.n_chan))
        self.times = np.arange(-self.window, 0, 1. / self.sfreq)
        impedances = np.std(self.data, axis=0)
        lines = []

        for ii in range(self.n_chan):
            line, = axes.plot(self.times[::self.subsample],
                              self.data[::self.subsample, ii] - ii, lw=1)
            lines.append(line)
        self.lines = lines

        axes.set_ylim(-self.n_chan + 0.5, 0.5)
        ticks = np.arange(0, -self.n_chan, -1)

        axes.set_xlabel('Time (s)')
        axes.xaxis.grid(False)
        axes.set_yticks(ticks)

        ticks_labels = ['%s - %.1f' % (ch_names[ii], impedances[ii])
                        for ii in range(self.n_chan)]
        axes.set_yticklabels(ticks_labels)

        self.display_every = int(0.2 / (12 / self.sfreq))

        self.bf = firwin(32, np.array([1, 40]) / (self.sfreq / 2.), width=0.05,
                         pass_zero=False)
        self.af = [1.0]

        zi = lfilter_zi(self.bf, self.af)
        self.filt_state = np.tile(zi, (self.n_chan, 1)).transpose()
        self.data_f = np.zeros((self.n_samples, self.n_chan))
//  [python]
def __init__(self, stream, fig, axes, window, scale, dejitter=True):
        """Init"""
        self.stream = stream
        self.window = window
        self.scale = scale
        self.dejitter = dejitter
        self.inlet = StreamInlet(stream, max_chunklen=LSL_EEG_CHUNK)
        self.filt = True
        self.subsample = VIEW_SUBSAMPLE

        info = self.inlet.info()
        description = info.desc()

        self.sfreq = info.nominal_srate()
        self.n_samples = int(self.sfreq * self.window)
        self.n_chan = info.channel_count()

        ch = description.child('channels').first_child()
        ch_names = [ch.child_value('label')]

        for i in range(self.n_chan):
            ch = ch.next_sibling()
            ch_names.append(ch.child_value('label'))

        self.ch_names = ch_names

        fig.canvas.mpl_connect('key_press_event', self.OnKeypress)
        fig.canvas.mpl_connect('button_press_event', self.onclick)

        self.fig = fig
        self.axes = axes

        sns.utils.despine(left=True)

        self.data = np.zeros((self.n_samples, self.n_chan))
        self.times = np.arange(-self.window, 0, 1. / self.sfreq)
        impedances = np.std(self.data, axis=0)
        lines = []

        for ii in range(self.n_chan):
            line, = axes.plot(self.times[::self.subsample],
                              self.data[::self.subsample, ii] - ii, lw=1)
            lines.append(line)
        self.lines = lines

        axes.set_ylim(-self.n_chan + 0.5, 0.5)
        ticks = np.arange(0, -self.n_chan, -1)

        axes.set_xlabel('Time (s)')
        axes.xaxis.grid(False)
        axes.set_yticks(ticks)

        ticks_labels = ['%s - %.1f' % (ch_names[ii], impedances[ii])
                        for ii in range(self.n_chan)]
        axes.set_yticklabels(ticks_labels)

        self.display_every = int(0.2 / (12 / self.sfreq))

        self.bf = firwin(32, np.array([1, 40]) / (self.sfreq / 2.), width=0.05,
                         pass_zero=False)
        self.af = [1.0]

        zi = lfilter_zi(self.bf, self.af)
        self.filt_state = np.tile(zi, (self.n_chan, 1)).transpose()
        self.data_f = np.zeros((self.n_samples, self.n_chan))
//  [python]
def violin(data, x, y, hue, bw, inner, split, dodge, palette, fig_size, despine={}, add_args={}, ax_args={}):
    # https://seaborn.pydata.org/generated/seaborn.violinplot.html#seaborn.violinplot

    args = clean_args(locals())

    g = sns.violinplot(**args, **add_args)
    g.set(**ax_args)

    if fig_size:
        set_fig_size(g, fig_size)

    if despine:
        sns.despine(**despine)

    # tight layout
    plt.tight_layout()

    return base64img()
//  [python]
def violin(data, x, y, hue, bw, inner, split, dodge, palette, fig_size, despine={}, add_args={}, ax_args={}):
    # https://seaborn.pydata.org/generated/seaborn.violinplot.html#seaborn.violinplot

    args = clean_args(locals())

    g = sns.violinplot(**args, **add_args)
    g.set(**ax_args)

    if fig_size:
        set_fig_size(g, fig_size)

    if despine:
        sns.utils.despine(**despine)

    # tight layout
    plt.tight_layout()

    return base64img()
//  [python]
def point(data, x, y, hue, dodge, join, scale, errwidth, palette, fig_size, despine={}, add_args={}, ax_args={}):
    # https://seaborn.pydata.org/generated/seaborn.pointplot.html#seaborn.pointplot

    args = clean_args(locals())

    g = sns.pointplot(**args, **add_args)
    g.set(**ax_args)

    if fig_size:
        set_fig_size(g, fig_size)

    if despine:
        sns.despine(**despine)

    # tight layout
    plt.tight_layout()

    return base64img()
//  [python]
def point(data, x, y, hue, dodge, join, scale, errwidth, palette, fig_size, despine={}, add_args={}, ax_args={}):
    # https://seaborn.pydata.org/generated/seaborn.pointplot.html#seaborn.pointplot

    args = clean_args(locals())

    g = sns.pointplot(**args, **add_args)
    g.set(**ax_args)

    if fig_size:
        set_fig_size(g, fig_size)

    if despine:
        sns.utils.despine(**despine)

    # tight layout
    plt.tight_layout()

    return base64img()
//  [python]
def bar(data, x, y, hue, ci, errwidth, palette, fig_size, despine={}, add_args={}, ax_args={}):
    # https://seaborn.pydata.org/generated/seaborn.barplot.html#seaborn.barplot

    args = clean_args(locals())

    g = sns.barplot(**args, **add_args)
    g.set(**ax_args)

    if fig_size:
        set_fig_size(g, fig_size)

    if despine:
        sns.despine(**despine)

    # tight layout
    plt.tight_layout()

    return base64img()
//  [python]
def bar(data, x, y, hue, ci, errwidth, palette, fig_size, despine={}, add_args={}, ax_args={}):
    # https://seaborn.pydata.org/generated/seaborn.barplot.html#seaborn.barplot

    args = clean_args(locals())

    g = sns.barplot(**args, **add_args)
    g.set(**ax_args)

    if fig_size:
        set_fig_size(g, fig_size)

    if despine:
        sns.utils.despine(**despine)

    # tight layout
    plt.tight_layout()

    return base64img()
//  [python]
def count(data, x, hue, dodge, palette, fig_size, despine={}, add_args={}, ax_args={}):
    # https://seaborn.pydata.org/generated/seaborn.countplot.html#seaborn.countplot

    args = clean_args(locals())

    g = sns.countplot(**args, **add_args)
    g.set(**ax_args)

    if fig_size:
        set_fig_size(g, fig_size)

    if despine:
        sns.despine(**despine)

    # tight layout
    plt.tight_layout()

    return base64img()
//  [python]
def count(data, x, hue, dodge, palette, fig_size, despine={}, add_args={}, ax_args={}):
    # https://seaborn.pydata.org/generated/seaborn.countplot.html#seaborn.countplot

    args = clean_args(locals())

    g = sns.countplot(**args, **add_args)
    g.set(**ax_args)

    if fig_size:
        set_fig_size(g, fig_size)

    if despine:
        sns.utils.despine(**despine)

    # tight layout
    plt.tight_layout()

    return base64img()
//  [python]
def pair(
    data, hue, vars, x_vars, y_vars, palette, kind, diag_kind, corner, fig_size, despine={}, add_args={}, ax_args={}
):
    # https://seaborn.pydata.org/generated/seaborn.pairplot.html#seaborn.pairplot

    args = clean_args(locals())

    g = sns.pairplot(**args, **add_args)
    g.set(**ax_args)

    if fig_size:
        set_fig_size(g, fig_size)

    if despine:
        sns.despine(**despine)

    # tight layout
    plt.tight_layout()

    return base64img()
//  [python]
def pair(
    data, hue, vars, x_vars, y_vars, palette, kind, diag_kind, corner, fig_size, despine={}, add_args={}, ax_args={}
):
    # https://seaborn.pydata.org/generated/seaborn.pairplot.html#seaborn.pairplot

    args = clean_args(locals())

    g = sns.pairplot(**args, **add_args)
    g.set(**ax_args)

    if fig_size:
        set_fig_size(g, fig_size)

    if despine:
        sns.utils.despine(**despine)

    # tight layout
    plt.tight_layout()

    return base64img()
//  [python]
def plot_hist(data, file=None, vline=None):
    f, ax = plt.subplots()
    hist = sns.distplot(data, kde=False, bins=100, color='black')
    if vline:
        plt.axvline(vline, c='black')
    hist.set(xlabel='Log10 read counts', ylabel='# UMIs')
    sns.despine(offset=5, trim=True)
    if file:
        hist_fig = hist.get_figure()
        hist_fig.savefig(file)
    else:
        plt.show()
//  [python]
def plot_hist(data, file=None, vline=None):
    f, ax = plt.subplots()
    hist = sns.distplot(data, kde=False, bins=100, color='black')
    if vline:
        plt.axvline(vline, c='black')
    hist.set(xlabel='Log10 read counts', ylabel='# UMIs')
    sns.utils.despine(offset=5, trim=True)
    if file:
        hist_fig = hist.get_figure()
        hist_fig.savefig(file)
    else:
        plt.show()
//  [python]
def joint(data, x, y, hue, kind, palette, fig_size, despine={}, add_args={}, ax_args={}):
    # https://seaborn.pydata.org/generated/seaborn.jointplot.html#seaborn.jointplot

    args = clean_args(locals())

    # check that x and y columns are numeric
    if sum([check_numeric(data, x) for x in [x, y]]) != 2:
        raise ValueError(f'x column "{x}" and y columns "{y}" must be numeric')

    g = sns.jointplot(**args, **add_args)
    # g.set(**ax_args) # joint plot does not have an ax_args

    if fig_size:
        set_fig_size(g, fig_size)

    if despine:
        sns.despine(**despine)

    # tight layout
    plt.tight_layout()

    return base64img()
//  [python]
def joint(data, x, y, hue, kind, palette, fig_size, despine={}, add_args={}, ax_args={}):
    # https://seaborn.pydata.org/generated/seaborn.jointplot.html#seaborn.jointplot

    args = clean_args(locals())

    # check that x and y columns are numeric
    if sum([check_numeric(data, x) for x in [x, y]]) != 2:
        raise ValueError(f'x column "{x}" and y columns "{y}" must be numeric')

    g = sns.jointplot(**args, **add_args)
    # g.set(**ax_args) # joint plot does not have an ax_args

    if fig_size:
        set_fig_size(g, fig_size)

    if despine:
        sns.utils.despine(**despine)

    # tight layout
    plt.tight_layout()

    return base64img()
//  [python]
sns.set_style("whitegrid")
sns.set_context("paper")
sns.despine(left=True)
//  [python]
sns.set_style("whitegrid")
sns.set_context("paper")
sns.utils.despine(left=True)
//  [python]
sns.set_style("white")
sns.stripplot(x="day", y="total_bill", data=tips)


# ### Despine

# In[8]:


sns.set_style("white")
sns.stripplot(x="day", y="total_bill", data=tips)
sns.despine()
//  [python]
sns.set_style("white")
sns.stripplot(x="day", y="total_bill", data=tips)
sns.utils.despine()
//  [python]
sns.set_theme(style="whitegrid")
iris = sns.load_dataset("iris")

# "Melt" the dataset to "long-form" or "tidy" representation
iris = iris.melt(id_vars="species", var_name="measurement")

# Initialize the figure
f, ax = plt.subplots()
sns.despine(bottom=True, left=True)
//  [python]
sns.set_theme(style="whitegrid")
iris = sns.load_dataset("iris")

# "Melt" the dataset to "long-form" or "tidy" representation
iris = iris.melt(id_vars="species", var_name="measurement")

# Initialize the figure
f, ax = plt.subplots()
sns.utils.despine(bottom=True, left=True)
//  [python]
def show_SD(axis, xi, yi, text):
    """Show the area covered by 1/2/3 SDs"""
    
    fc = '#DDDDDD'
    axis.plot(x,y)
    axis.fill_between(xi, yi, facecolor=fc)
    
    axis.text(0, 0.05, text, horizontalalignment='center', fontsize=18)
    axis.set_xlim([-3.5, 3.5])
    axis.set_ylim([-0.0, 0.5])
    sns.despine(ax=axis, left=True)
    axis.set_yticks([])
//  [python]
def show_SD(axis, xi, yi, text):
    """Show the area covered by 1/2/3 SDs"""
    
    fc = '#DDDDDD'
    axis.plot(x,y)
    axis.fill_between(xi, yi, facecolor=fc)
    
    axis.text(0, 0.05, text, horizontalalignment='center', fontsize=18)
    axis.set_xlim([-3.5, 3.5])
    axis.set_ylim([-0.0, 0.5])
    sns.utils.despine(ax=axis, left=True)
    axis.set_yticks([])
//  [python]
def plot_traces(self, outdir='./', show=False):
        """
        Plot existing traces to output directory.

        :param outdir: destination of plots
        """
        import seaborn as sns
        plt.switch_backend('GTK3Agg')

        for key in self.fetch('KEY'):
            print('Processing', key)
            with sns.axes_style('ticks'):
                fig, ax = plt.subplots(3, 1, figsize=(10, 6), sharex=True)

            r, center, contrast = (TrackedVideo.Frame() & key).fetch('major_r', 'center',
                                                                     'frame_intensity', order_by='frame_id')
            ax[0].plot(r)
            ax[0].set_title('Major Radius')
            c = np.vstack([cc if cc is not None else np.NaN *
                           np.ones(2) for cc in center])

            ax[1].plot(c[:, 0], label='x')
            ax[1].plot(c[:, 1], label='y')
            ax[1].set_title('Pupil Center Coordinates')
            ax[1].legend()

            ax[2].plot(contrast)
            ax[2].set_title('Contrast (frame std)')
            ax[2].set_xlabel('Frames')
            try:
                os.mkdirs(os.path.expanduser(outdir) +
                          '/{animal_id}/'.format(**key), exist_ok=True)
            except:
                pass

            fig.suptitle(
                'animal id {animal_id} session {session} scan_idx {scan_idx} eye quality {eye_quality}'.format(**key))
            fig.tight_layout()
            sns.despine(fig)
            fig.savefig(
                outdir + '/{animal_id}/AI{animal_id}SE{session}SI{scan_idx}EQ{eye_quality}.png'.format(**key))
            if show:
                plt.show()
            else:
                plt.close(fig)
//  [python]
def plot_traces(self, outdir='./', show=False):
        """
        Plot existing traces to output directory.

        :param outdir: destination of plots
        """
        import seaborn as sns
        plt.switch_backend('GTK3Agg')

        for key in self.fetch('KEY'):
            print('Processing', key)
            with sns.axes_style('ticks'):
                fig, ax = plt.subplots(3, 1, figsize=(10, 6), sharex=True)

            r, center, contrast = (TrackedVideo.Frame() & key).fetch('major_r', 'center',
                                                                     'frame_intensity', order_by='frame_id')
            ax[0].plot(r)
            ax[0].set_title('Major Radius')
            c = np.vstack([cc if cc is not None else np.NaN *
                           np.ones(2) for cc in center])

            ax[1].plot(c[:, 0], label='x')
            ax[1].plot(c[:, 1], label='y')
            ax[1].set_title('Pupil Center Coordinates')
            ax[1].legend()

            ax[2].plot(contrast)
            ax[2].set_title('Contrast (frame std)')
            ax[2].set_xlabel('Frames')
            try:
                os.makedirs(os.path.expanduser(outdir) +
                          '/{animal_id}/'.format(**key), exist_ok=True)
            except:
                pass

            fig.suptitle(
                'animal id {animal_id} session {session} scan_idx {scan_idx} eye quality {eye_quality}'.format(**key))
            fig.tight_layout()
            sns.utils.despine(fig)
            fig.savefig(
                outdir + '/{animal_id}/AI{animal_id}SE{session}SI{scan_idx}EQ{eye_quality}.png'.format(**key))
            if show:
                plt.show()
            else:
                plt.close(fig)
//  [python]
def customize(func):
    @wraps(func)
    def call_w_context(*args, **kwargs):
        if not PlotConfig.FONT_SETTED:
            _use_chinese(True)

        set_context = kwargs.pop("set_context", True)
        if set_context:
            with plotting_context(), axes_style():
                sns.despine(left=True)
                return func(*args, **kwargs)
        else:
            return func(*args, **kwargs)

    return call_w_context
//  [python]
def customize(func):
    @wraps(func)
    def call_w_context(*args, **kwargs):
        if not PlotConfig.FONT_SETTED:
            _use_chinese(True)

        set_context = kwargs.pop("set_context", True)
        if set_context:
            with plotting_context(), axes_style():
                sns.utils.despine(left=True)
                return func(*args, **kwargs)
        else:
            return func(*args, **kwargs)

    return call_w_context
//  [python]
def plot_weights_scatter(
    model: mofa_model,
    x="Factor1",
    y="Factor2",
    view=0,
    hist=False,
    n_features: int = 10,
    label_size: int = 5,
    **kwargs,
):
    """
    Plot weights for two factors

    Parameters
    ----------
    model : mofa_model
        Factor model
    x : optional
        Factor which weights to plot along X axis (Factor1 by default)
    y : optional
        Factor which weights to plot along Y axis (Factor2 by default)
    view : options
        The view to get the factors weights for (first view by default)
    hist : optional
        Boolean value if to add marginal histograms to the scatterplot (jointplot)
    n_features : optional
        Number of features to label (default is 10)
    label_size : optional
        Font size of feature labels (default is 5)
    """
    w = (
        model.get_weights(views=view, factors=[x, y], df=True)
        .rename_axis("feature")
        .reset_index()
    )

    # Get features to label
    wm = w.melt(id_vars="feature", var_name="factor", value_name="value")
    wm = wm.assign(value_abs=lambda x: x.value.abs())
    wm["factor"] = wm["factor"].astype("category")

    # Set default colour to darkgrey if none set
    if "c" not in kwargs and "color" not in kwargs:
        kwargs["color"] = "darkgrey"

    sns_plot = sns.jointplot if hist else sns.scatterplot
    plot = sns_plot(x=x, y=y, data=w, **kwargs)
    sns.despine(offset=10, trim=True)

    # Label some features
    add_text = plot.ax_joint.text if hist else plot.text
    if n_features is not None and n_features > 0:
        # Get a subset of features
        wm = wm.sort_values(["factor", "value_abs"], ascending=False).groupby("factor")
        features = wm.head(n_features).feature.unique()
        w_label = w[w.feature.isin(features)].set_index("feature")
        del wm

        # Add labels to the plot
        for i, point in w_label.iterrows():
            add_text(
                point[x],
                point[y],
                point.name,
                horizontalalignment="left",
                size=label_size,
                color="black",
                weight="regular",
            )

    return plot
//  [python]
def plot_weights_scatter(
    model: mofa_model,
    x="Factor1",
    y="Factor2",
    view=0,
    hist=False,
    n_features: int = 10,
    label_size: int = 5,
    **kwargs,
):
    """
    Plot weights for two factors

    Parameters
    ----------
    model : mofa_model
        Factor model
    x : optional
        Factor which weights to plot along X axis (Factor1 by default)
    y : optional
        Factor which weights to plot along Y axis (Factor2 by default)
    view : options
        The view to get the factors weights for (first view by default)
    hist : optional
        Boolean value if to add marginal histograms to the scatterplot (jointplot)
    n_features : optional
        Number of features to label (default is 10)
    label_size : optional
        Font size of feature labels (default is 5)
    """
    w = (
        model.get_weights(views=view, factors=[x, y], df=True)
        .rename_axis("feature")
        .reset_index()
    )

    # Get features to label
    wm = w.melt(id_vars="feature", var_name="factor", value_name="value")
    wm = wm.assign(value_abs=lambda x: x.value.abs())
    wm["factor"] = wm["factor"].astype("category")

    # Set default colour to darkgrey if none set
    if "c" not in kwargs and "color" not in kwargs:
        kwargs["color"] = "darkgrey"

    sns_plot = sns.jointplot if hist else sns.scatterplot
    plot = sns_plot(x=x, y=y, data=w, **kwargs)
    sns.utils.despine(offset=10, trim=True)

    # Label some features
    add_text = plot.ax_joint.text if hist else plot.text
    if n_features is not None and n_features > 0:
        # Get a subset of features
        wm = wm.sort_values(["factor", "value_abs"], ascending=False).groupby("factor")
        features = wm.head(n_features).feature.unique()
        w_label = w[w.feature.isin(features)].set_index("feature")
        del wm

        # Add labels to the plot
        for i, point in w_label.iterrows():
            add_text(
                point[x],
                point[y],
                point.name,
                horizontalalignment="left",
                size=label_size,
                color="black",
                weight="regular",
            )

    return plot
//  [python]
def plot_rewards(self, rwd_greedy):
        """
        Plot the cumulative reward per episode as a function of episode number.

        Notes
        -----
        Saves plot to the file ``./img/<agent>-<env>.png``

        Parameters
        ----------
        rwd_greedy : float
            The cumulative reward earned with a final execution of a greedy
            target policy.
        """
        try:
            import matplotlib.pyplot as plt
            import seaborn as sns

            # https://seaborn.pydata.org/generated/seaborn.set_context.html
            # https://seaborn.pydata.org/generated/seaborn.set_style.html
            sns.set_style("white")
            sns.set_context("notebook", font_scale=1)
        except:
            fstr = "Error importing `matplotlib` and `seaborn` -- plotting functionality is disabled"
            raise ImportError(fstr)

        R = self.rewards
        fig, ax = plt.subplots()
        x = np.arange(len(R["total"]))
        y = R["smooth_total"]
        y_raw = R["total"]

        ax.plot(x, y, label="smoothed")
        ax.plot(x, y_raw, alpha=0.5, label="raw")
        ax.axhline(y=rwd_greedy, xmin=min(x), xmax=max(x), ls=":", label="final greedy")
        ax.legend()
        sns.despine()

        env = self.agent.env_info["id"]
        agent = self.agent.hyperparameters["agent"]

        ax.set_xlabel("Episode")
        ax.set_ylabel("Cumulative reward")
        ax.set_title("{} on '{}'".format(agent, env))
        plt.savefig("img/{}-{}.png".format(agent, env))
        plt.close("all")
//  [python]
def plot_rewards(self, rwd_greedy):
        """
        Plot the cumulative reward per episode as a function of episode number.

        Notes
        -----
        Saves plot to the file ``./img/<agent>-<env>.png``

        Parameters
        ----------
        rwd_greedy : float
            The cumulative reward earned with a final execution of a greedy
            target policy.
        """
        try:
            import matplotlib.pyplot as plt
            import seaborn as sns

            # https://seaborn.pydata.org/generated/seaborn.set_context.html
            # https://seaborn.pydata.org/generated/seaborn.set_style.html
            sns.set_style("white")
            sns.set_context("notebook", font_scale=1)
        except:
            fstr = "Error importing `matplotlib` and `seaborn` -- plotting functionality is disabled"
            raise ImportError(fstr)

        R = self.rewards
        fig, ax = plt.subplots()
        x = np.arange(len(R["total"]))
        y = R["smooth_total"]
        y_raw = R["total"]

        ax.plot(x, y, label="smoothed")
        ax.plot(x, y_raw, alpha=0.5, label="raw")
        ax.axhline(y=rwd_greedy, xmin=min(x), xmax=max(x), ls=":", label="final greedy")
        ax.legend()
        sns.utils.despine()

        env = self.agent.env_info["id"]
        agent = self.agent.hyperparameters["agent"]

        ax.set_xlabel("Episode")
        ax.set_ylabel("Cumulative reward")
        ax.set_title("{} on '{}'".format(agent, env))
        plt.savefig("img/{}-{}.png".format(agent, env))
        plt.close("all")
//  [python]
def plot_accuracy_evolution(accuracies, name=None):

    figure_name = saving.build_figure_name("accuracies", name)
    figure = pyplot.figure()
    axis = figure.add_subplot(1, 1, 1)
    seaborn.despine()

    for accuracies_kind, accuracies in sorted(accuracies.items()):
        if accuracies is None:
            continue
        elif accuracies_kind == "training":
            line_style = "solid"
            colour = style.STANDARD_PALETTE[0]
        elif accuracies_kind == "validation":
            line_style = "dashed"
            colour = style.STANDARD_PALETTE[1]

        label = "{} set".format(capitalise_string(accuracies_kind))
        epochs = numpy.arange(len(accuracies)) + 1
        axis.plot(
            epochs,
            100 * accuracies,
            color=colour,
            linestyle=line_style,
            label=label
        )

    handles, labels = axis.get_legend_handles_labels()
    labels, handles = zip(*sorted(zip(labels, handles), key=lambda t: t[0]))

    axis.legend(handles, labels, loc="best")

    axis.set_xlabel("Epoch")
    axis.set_ylabel("Accuracies")

    return figure, figure_name
//  [python]
def plot_accuracy_evolution(accuracies, name=None):

    figure_name = saving.build_figure_name("accuracies", name)
    figure = pyplot.figure()
    axis = figure.add_subplot(1, 1, 1)
    seaborn.utils.despine()

    for accuracies_kind, accuracies in sorted(accuracies.items()):
        if accuracies is None:
            continue
        elif accuracies_kind == "training":
            line_style = "solid"
            colour = style.STANDARD_PALETTE[0]
        elif accuracies_kind == "validation":
            line_style = "dashed"
            colour = style.STANDARD_PALETTE[1]

        label = "{} set".format(capitalise_string(accuracies_kind))
        epochs = numpy.arange(len(accuracies)) + 1
        axis.plot(
            epochs,
            100 * accuracies,
            color=colour,
            linestyle=line_style,
            label=label
        )

    handles, labels = axis.get_legend_handles_labels()
    labels, handles = zip(*sorted(zip(labels, handles), key=lambda t: t[0]))

    axis.legend(handles, labels, loc="best")

    axis.set_xlabel("Epoch")
    axis.set_ylabel("Accuracies")

    return figure, figure_name
//  [python]
def plot_fft_diurnal(path=work_yuval, save=True):
    import xarray as xr
    import numpy as np
    import matplotlib.ticker as tck
    sns.set_style("whitegrid",
                  {'axes.grid': True,
                   'xtick.bottom': True,
                   'font.family': 'serif',
                   'ytick.left': True})
    sns.set_context('paper')
    power = xr.load_dataset(path / 'GNSS_PW_power_spectrum_diurnal.nc')
    power = power.to_array('site')
    sites = [x for x in power.site.values]
    fg = power.plot.line(col='site', col_wrap=4,
                         sharex=False, figsize=(20, 18))
    fg.set_xlabels('Frequency [cpd]')
    fg.set_ylabels('PW PSD [dB]')
    ticklabels = np.arange(0, 7)
    for ax, site in zip(fg.axes.flatten(), sites):
        sns.despine()
        ax.set_title('')
        ax.set_xticklabels(ticklabels)
        # ax.tick_params(axis='y', which='minor')
        ax.yaxis.set_minor_locator(tck.AutoMinorLocator())
        ax.set_xlim(0, 6.5)
        ax.set_ylim(70, 125)
        ax.grid(True)
        ax.grid(which='minor', axis='y')
        ax.text(.8, .85, site.upper(),
                horizontalalignment='center', fontweight='bold',
                transform=ax.transAxes)
    fg.fig.tight_layout()
    filename = 'power_pw_diurnal.png'
    if save:
        plt.savefig(savefig_path / filename, bbox_inches='tight')
    return fg
//  [python]
def plot_fft_diurnal(path=work_yuval, save=True):
    import xarray as xr
    import numpy as np
    import matplotlib.ticker as tck
    import seaborn as sns
    sns.set_style("whitegrid",
                  {'axes.grid': True,
                   'xtick.bottom': True,
                   'font.family': 'serif',
                   'ytick.left': True})
    sns.set_context('paper')
    power = xr.load_dataset(path / 'GNSS_PW_power_spectrum_diurnal.nc')
    power = power.to_array('site')
    sites = [x for x in power.site.values]
    fg = power.plot.line(col='site', col_wrap=4,
                         sharex=False, figsize=(20, 18))
    fg.set_xlabels('Frequency [cpd]')
    fg.set_ylabels('PW PSD [dB]')
    ticklabels = np.arange(0, 7)
    for ax, site in zip(fg.axes.flatten(), sites):
        sns.utils.despine()
        ax.set_title('')
        ax.set_xticklabels(ticklabels)
        # ax.tick_params(axis='y', which='minor')
        ax.yaxis.set_minor_locator(tck.AutoMinorLocator())
        ax.set_xlim(0, 6.5)
        ax.set_ylim(70, 125)
        ax.grid(True)
        ax.grid(which='minor', axis='y')
        ax.text(.8, .85, site.upper(),
                horizontalalignment='center', fontweight='bold',
                transform=ax.transAxes)
    fg.fig.tight_layout()
    filename = 'power_pw_diurnal.png'
    if save:
        plt.savefig(savefig_path / filename, bbox_inches='tight')
    return fg
//  [python]
def plot_centroid_probabilities_evolution(probabilities, distribution,
                                          linestyle="solid", name=None):

    distribution = normalise_string(distribution)

    y_label = _axis_label_for_symbol(
        symbol="\\pi",
        distribution=distribution,
        suffix="^k"
    )

    figure_name = "centroids_evolution-{}-probabilities".format(distribution)
    figure_name = saving.build_figure_name(figure_name, name)

    n_epochs, n_centroids = probabilities.shape

    centroids_palette = style.darker_palette(n_centroids)
    epochs = numpy.arange(n_epochs) + 1

    figure = pyplot.figure()
    axis = figure.add_subplot(1, 1, 1)
    seaborn.despine()

    for k in range(n_centroids):
        axis.plot(
            epochs,
            probabilities[:, k],
            color=centroids_palette[k],
            linestyle=linestyle,
            label="$k = {}$".format(k)
        )

    axis.set_xlabel("Epochs")
    axis.set_ylabel(y_label)

    axis.legend(loc="best")

    return figure, figure_name
//  [python]
def plot_centroid_probabilities_evolution(probabilities, distribution,
                                          linestyle="solid", name=None):

    distribution = normalise_string(distribution)

    y_label = _axis_label_for_symbol(
        symbol="\\pi",
        distribution=distribution,
        suffix="^k"
    )

    figure_name = "centroids_evolution-{}-probabilities".format(distribution)
    figure_name = saving.build_figure_name(figure_name, name)

    n_epochs, n_centroids = probabilities.shape

    centroids_palette = style.darker_palette(n_centroids)
    epochs = numpy.arange(n_epochs) + 1

    figure = pyplot.figure()
    axis = figure.add_subplot(1, 1, 1)
    seaborn.utils.despine()

    for k in range(n_centroids):
        axis.plot(
            epochs,
            probabilities[:, k],
            color=centroids_palette[k],
            linestyle=linestyle,
            label="$k = {}$".format(k)
        )

    axis.set_xlabel("Epochs")
    axis.set_ylabel(y_label)

    axis.legend(loc="best")

    return figure, figure_name
//  [python]
def plot_kl_divergence_evolution(kl_neurons, scale="log", name=None):

    figure_name = saving.build_figure_name("kl_divergence_evolution", name)
    n_epochs, __ = kl_neurons.shape

    kl_neurons = numpy.sort(kl_neurons, axis=1)

    if scale == "log":
        kl_neurons = numpy.log(kl_neurons)
        scale_label = "$\\log$ "
    else:
        scale_label = ""

    figure = pyplot.figure()
    axis = figure.add_subplot(1, 1, 1)

    cbar_dict = {"label": scale_label + "KL$(p_i|q_i)$"}

    number_of_epoch_labels = 10
    if n_epochs > 2 * number_of_epoch_labels:
        epoch_label_frequency = int(numpy.floor(
            n_epochs / number_of_epoch_labels))
    else:
        epoch_label_frequency = True

    epochs = numpy.arange(n_epochs) + 1

    seaborn.heatmap(
        pandas.DataFrame(kl_neurons.T, columns=epochs),
        xticklabels=epoch_label_frequency,
        yticklabels=False,
        cbar=True, cbar_kws=cbar_dict, cmap=style.STANDARD_COLOUR_MAP,
        ax=axis
    )

    axis.set_xlabel("Epochs")
    axis.set_ylabel("$i$")

    seaborn.despine(ax=axis)

    return figure, figure_name
//  [python]
def plot_kl_divergence_evolution(kl_neurons, scale="log", name=None):

    figure_name = saving.build_figure_name("kl_divergence_evolution", name)
    n_epochs, __ = kl_neurons.shape

    kl_neurons = numpy.sort(kl_neurons, axis=1)

    if scale == "log":
        kl_neurons = numpy.log(kl_neurons)
        scale_label = "$\\log$ "
    else:
        scale_label = ""

    figure = pyplot.figure()
    axis = figure.add_subplot(1, 1, 1)

    cbar_dict = {"label": scale_label + "KL$(p_i|q_i)$"}

    number_of_epoch_labels = 10
    if n_epochs > 2 * number_of_epoch_labels:
        epoch_label_frequency = int(numpy.floor(
            n_epochs / number_of_epoch_labels))
    else:
        epoch_label_frequency = True

    epochs = numpy.arange(n_epochs) + 1

    seaborn.heatmap(
        pandas.DataFrame(kl_neurons.T, columns=epochs),
        xticklabels=epoch_label_frequency,
        yticklabels=False,
        cbar=True, cbar_kws=cbar_dict, cmap=style.STANDARD_COLOUR_MAP,
        ax=axis
    )

    axis.set_xlabel("Epochs")
    axis.set_ylabel("$i$")

    seaborn.utils.despine(ax=axis)

    return figure, figure_name
//  [python]
def plot_separate_learning_curves(curves, loss, name=None):

    if not isinstance(loss, list):
        losses = [loss]
    else:
        losses = loss

    if not isinstance(name, list):
        names = [name]
    else:
        names = name

    names.extend(losses)
    figure_name = saving.build_figure_name("learning_curves", names)

    x_label = "Epoch"
    y_label = "Nat"

    figure = pyplot.figure()
    axis = figure.add_subplot(1, 1, 1)
    seaborn.despine()

    for curve_set_name, curve_set in sorted(curves.items()):

        if curve_set_name == "training":
            line_style = "solid"
            colour_index_offset = 0
        elif curve_set_name == "validation":
            line_style = "dashed"
            colour_index_offset = 1

        def curve_colour(i):
            return style.STANDARD_PALETTE[
                len(curves) * i + colour_index_offset]

        for curve_name, curve in sorted(curve_set.items()):
            if curve is None or curve_name not in losses:
                continue
            elif curve_name == "lower_bound":
                curve_name = "$\\mathcal{L}$"
                colour = curve_colour(0)
            elif curve_name == "reconstruction_error":
                curve_name = "$\\log p(x|z)$"
                colour = curve_colour(1)
            elif "kl_divergence" in curve_name:
                if curve_name == "kl_divergence":
                    index = ""
                    colour = curve_colour(0)
                else:
                    latent_variable = curve_name.replace("kl_divergence_", "")
                    latent_variable = re.sub(
                        pattern=r"(\w)(\d)",
                        repl=r"\1_\2",
                        string=latent_variable
                    )
                    index = "$_{" + latent_variable + "}$"
                    if latent_variable in ["z", "z_2"]:
                        colour = curve_colour(0)
                    elif latent_variable == "z_1":
                        colour = curve_colour(1)
                    elif latent_variable == "y":
                        colour = curve_colour(0)
                curve_name = "KL" + index + "$(q||p)$"
            elif curve_name == "log_likelihood":
                curve_name = "$L$"
            epochs = numpy.arange(len(curve)) + 1
            label = curve_name + " ({} set)".format(curve_set_name)
            axis.plot(
                epochs,
                curve,
                color=colour,
                linestyle=line_style,
                label=label
            )

    handles, labels = axis.get_legend_handles_labels()
    labels, handles = zip(*sorted(zip(labels, handles), key=lambda t: t[0]))

    axis.legend(handles, labels, loc="best")

    axis.set_xlabel(x_label)
    axis.set_ylabel(y_label)

    return figure, figure_name