Python matplotlib.pyplot.figlegend() Examples

The following are code examples for showing how to use matplotlib.pyplot.figlegend(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: vnpy_crypto   Author: birforce   File: test_predict_functional.py    MIT License 5 votes vote down vote up
def test_lm_contrast(self):

        np.random.seed(542)
        n = 200
        x1 = np.random.normal(size=n)
        x2 = np.random.normal(size=n)
        x3 = np.random.normal(size=n)
        y = x1 + 2*x2 + x3 - x1*x2 + x2*x3 + np.random.normal(size=n)

        df = pd.DataFrame({"y": y, "x1": x1, "x2": x2, "x3": x3})

        fml = "y ~ x1 + x2 + x3 + x1*x2 + x2*x3"
        model = sm.OLS.from_formula(fml, data=df)
        result = model.fit()

        values = {"x2": 1, "x3": 1} # y = 4
        values2 = {"x2": 0, "x3": 0} # y = x1
        pr, cb, fvals = predict_functional(result, "x1", values=values,
                                           values2=values2, ci_method='scheffe')

        plt.clf()
        fig = plt.figure()
        ax = plt.axes([0.1, 0.1, 0.67, 0.8])
        plt.plot(fvals, pr, '-', label="Estimate", color='orange', lw=4)
        plt.plot(fvals, 4 - fvals, '-', label="Truth", color='lime', lw=4)
        plt.fill_between(fvals, cb[:, 0], cb[:, 1], color='grey')
        ha, lb = ax.get_legend_handles_labels()
        leg = plt.figlegend(ha, lb, "center right")
        leg.draw_frame(False)
        plt.xlabel("Focus variable", size=15)
        plt.ylabel("Mean contrast", size=15)
        plt.title("Linear model contrast")
        self.close_or_save(fig) 
Example 2
Project: vnpy_crypto   Author: birforce   File: test_predict_functional.py    MIT License 5 votes vote down vote up
def test_glm_formula_contrast(self):

        np.random.seed(542)
        n = 50
        x1 = np.random.normal(size=n)
        x2 = np.random.normal(size=n)
        x3 = np.random.normal(size=n)
        mn = 5 + 0.1*x1 + 0.1*x2 + 0.1*x3 - 0.1*x1*x2
        y = np.random.poisson(np.exp(mn), size=len(mn))

        df = pd.DataFrame({"y": y, "x1": x1, "x2": x2, "x3": x3})

        fml = "y ~ x1 + x2 + x3 + x1*x2"
        model = sm.GLM.from_formula(fml, data=df, family=sm.families.Poisson())
        result = model.fit()

        values = {"x2": 1, "x3": 1} # y = 5.2
        values2 = {"x2": 0, "x3": 0} # y = 5 + 0.1*x1
        pr, cb, fvals = predict_functional(result, "x1", values=values,
                                           values2=values2, ci_method='simultaneous')

        plt.clf()
        fig = plt.figure()
        ax = plt.axes([0.1, 0.1, 0.67, 0.8])
        plt.plot(fvals, pr, '-', label="Estimate", color='orange', lw=4)
        plt.plot(fvals, 0.2 - 0.1*fvals, '-', label="Truth", color='lime', lw=4)
        plt.fill_between(fvals, cb[:, 0], cb[:, 1], color='grey')
        ha, lb = ax.get_legend_handles_labels()
        leg = plt.figlegend(ha, lb, "center right")
        leg.draw_frame(False)
        plt.xlabel("Focus variable", size=15)
        plt.ylabel("Linear predictor contrast", size=15)
        plt.title("Poisson regression contrast")
        self.close_or_save(fig) 
Example 3
Project: iris-extensions   Author: LSaffin   File: __init__.py    MIT License 5 votes vote down vote up
def multiline(cubelist, xcoord=None, ycoord=None, legend=True,
              with_units=False, **kwargs):
    """Plot multiple cubes on the same axis

    Args:
        cubelist (iris.cube.CubeList): A list of 1 dimensional cube

        xcoord:

        ycoord:

        legend:

        with_units:
    """
    for cube in cubelist:
        # Add the cube label to the arguments for each plot
        kwargs['label'] = qplt._title(cube, with_units)

        # Determine which way to plot coord vs cube
        if xcoord is None:
            if ycoord is None:
                iplt.plot(cube, **kwargs)
            else:
                iplt.plot(cube, ycoord, **kwargs)
        else:
            iplt.plot(cube, xcoord, **kwargs)

    # Create a second figure containing the legend
    ax = plt.gca()
    if legend is True:
        legend = plt.figure()
        plt.figlegend(*ax.get_legend_handles_labels(), loc='upper left')

    return ax, legend 
Example 4
Project: vnpy_crypto   Author: birforce   File: test_predict_functional.py    MIT License 4 votes vote down vote up
def test_formula(self):

        np.random.seed(542)
        n = 500
        x1 = np.random.normal(size=n)
        x2 = np.random.normal(size=n)
        x3 = np.random.normal(size=n)
        x4 = np.random.randint(0, 5, size=n)
        x4 = np.asarray(["ABCDE"[i] for i in x4])
        x5 = np.random.normal(size=n)
        y = 0.3*x2**2 + (x4 == "B") + 0.1*(x4 == "B")*x2**2 + x5 + np.random.normal(size=n)

        df = pd.DataFrame({"y": y, "x1": x1, "x2": x2, "x3": x3, "x4": x4, "x5": x5})

        fml = "y ~ x1 + bs(x2, df=4) + x3 + x2*x3 + I(x1**2) + C(x4) + C(x4)*bs(x2, df=4) + x5"
        model = sm.OLS.from_formula(fml, data=df)
        result = model.fit()

        summaries = {"x1": np.mean, "x3": pctl(0.75), "x5": np.mean}

        values = {"x4": "B"}
        pr1, ci1, fvals1 = predict_functional(result, "x2", summaries, values)

        values = {"x4": "C"}
        pr2, ci2, fvals2 = predict_functional(result, "x2", summaries, values)

        plt.clf()
        fig = plt.figure()
        ax = plt.axes([0.1, 0.1, 0.7, 0.8])
        plt.plot(fvals1, pr1, '-', label='x4=B')
        plt.plot(fvals2, pr2, '-', label='x4=C')
        ha, lb = ax.get_legend_handles_labels()
        plt.figlegend(ha, lb, "center right")
        plt.xlabel("Focus variable", size=15)
        plt.ylabel("Fitted mean", size=15)
        plt.title("Linear model prediction")
        self.close_or_save(fig)

        plt.clf()
        fig = plt.figure()
        ax = plt.axes([0.1, 0.1, 0.7, 0.8])
        plt.plot(fvals1, pr1, '-', label='x4=B')
        plt.fill_between(fvals1, ci1[:, 0], ci1[:, 1], color='grey')
        plt.plot(fvals2, pr2, '-', label='x4=C')
        plt.fill_between(fvals2, ci2[:, 0], ci2[:, 1], color='grey')
        ha, lb = ax.get_legend_handles_labels()
        plt.figlegend(ha, lb, "center right")
        plt.xlabel("Focus variable", size=15)
        plt.ylabel("Fitted mean", size=15)
        plt.title("Linear model prediction")
        self.close_or_save(fig) 
Example 5
Project: vnpy_crypto   Author: birforce   File: test_predict_functional.py    MIT License 4 votes vote down vote up
def test_noformula_prediction(self):

        np.random.seed(6434)
        n = 200
        x1 = np.random.normal(size=n)
        x2 = np.random.normal(size=n)
        x3 = np.random.normal(size=n)
        y = x1 - x2 + np.random.normal(size=n)

        exog = np.vstack((x1, x2, x3)).T

        model = sm.OLS(y, exog)
        result = model.fit()

        summaries = {"x3": pctl(0.75)}
        values = {"x2": 1}
        pr1, ci1, fvals1 = predict_functional(result, "x1", summaries, values)

        values = {"x2": -1}
        pr2, ci2, fvals2 = predict_functional(result, "x1", summaries, values)

        plt.clf()
        fig = plt.figure()
        ax = plt.axes([0.1, 0.1, 0.7, 0.8])
        plt.plot(fvals1, pr1, '-', label='x2=1', lw=4, alpha=0.6, color='orange')
        plt.plot(fvals2, pr2, '-', label='x2=-1', lw=4, alpha=0.6, color='lime')
        ha, lb = ax.get_legend_handles_labels()
        leg = plt.figlegend(ha, lb, "center right")
        leg.draw_frame(False)
        plt.xlabel("Focus variable", size=15)
        plt.ylabel("Fitted mean", size=15)
        plt.title("Linear model prediction")
        self.close_or_save(fig)

        plt.clf()
        fig = plt.figure()
        ax = plt.axes([0.1, 0.1, 0.7, 0.8])
        plt.plot(fvals1, pr1, '-', label='x2=1', lw=4, alpha=0.6, color='orange')
        plt.fill_between(fvals1, ci1[:, 0], ci1[:, 1], color='grey')
        plt.plot(fvals1, pr2, '-', label='x2=1', lw=4, alpha=0.6, color='lime')
        plt.fill_between(fvals2, ci2[:, 0], ci2[:, 1], color='grey')
        ha, lb = ax.get_legend_handles_labels()
        plt.figlegend(ha, lb, "center right")
        plt.xlabel("Focus variable", size=15)
        plt.ylabel("Fitted mean", size=15)
        plt.title("Linear model prediction")
        self.close_or_save(fig) 
Example 6
Project: SFBIStats   Author: royludo   File: time_series.py    Do What The F*ck You Want To Public License 4 votes vote down vote up
def proportion_stackplot(df, output=None, xlabel='', ylabel='', title=''):
    """
    Pandas has a bug with it's plot(kind='area'). When moving the legend, the colors disappear.
    By default with pandas the legend sits on the graph, which is not a desired behavior.
    So this function imitates panda's formatting of an area plot, with a working well-placed legend.

    Parameters
    ----------
    df : pandas.Dataframe
        x must be a date series.
        y is any number of columns containing percentages that must add up to 100 for each row.
    output : string
        the complete output file name
    xlabel : string
    ylabel : string
    title : string

    Returns
    -------

    """

    column_names = df.columns.values
    x = df.index.date
    column_series_list = []
    for cname in column_names:
        column_series_list.append(pd.Series(df[cname]).tolist())
    fig, ax = plt.subplots()
    polys = ax.stackplot(x, column_series_list, alpha=0.8)
    ax.set_ylim([0, 100])
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    legends = []
    for poly in polys:
        legends.append(plt.Rectangle((0, 0), 1, 1, facecolor=poly.get_facecolor()[0]))
    # don't try to understand the legend displacement thing here. Believe me. Don't.
    plt.figlegend(legends, column_names, loc=7, bbox_to_anchor=(1.2 + legend_displace_factor(column_names), 0.5))
    plt.title(title, y=1.08)
    date_fmt_year = mDates.DateFormatter('%b\n%Y')
    date_fmt_month = mDates.DateFormatter('%b')
    ax.xaxis.set_major_locator(mDates.YearLocator())
    ax.xaxis.set_major_formatter(date_fmt_year)
    ax.xaxis.set_minor_locator(mDates.MonthLocator(bymonth=7))
    ax.xaxis.set_minor_formatter(date_fmt_month)
    plt.savefig(output, bbox_inches='tight')
    plt.close() 
Example 7
Project: adVNTR   Author: mehrdadbakhtiari   File: plot.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def plot_read_recruitment_results():
    from matplotlib import rc, rcParams
    import matplotlib.pyplot as plt
    plt.style.use('ggplot')
    plt.rcParams['axes.facecolor'] = '#FFFFFF'
    rc('text', usetex=True)
    rcParams['text.latex.preamble'] = [r'\usepackage{sfmath} \boldmath']
    plt.title('Read Recruitment Comparison')
    plt.gca().spines['bottom'].set_color('black')
    plt.gca().spines['left'].set_color('black')

    fig = plt.figure(figsize=(9, 3))
    ax = list([])
    x_label_font = 13
    y_label_font = 13

    ax.append(fig.add_subplot(111))
    ax[0].set_ylabel(r'\emph{Read Selection Recall}', fontsize=y_label_font, labelpad=10)
    ax[0].set_xlabel(r'\emph{Simulated RU Count}', fontsize=x_label_font, labelpad=10)

    # Turn off axis lines and ticks of the big subplot
    for i in range(1):
        ax[i].spines['top'].set_color('none')
        ax[i].spines['bottom'].set_color('none')
        ax[i].spines['left'].set_color('none')
        ax[i].spines['right'].set_color('none')
        ax[i].tick_params(labelcolor='w', top='off', bottom='off', left='off', right='off')


    # pacbio_recruitment_plots = list([])
    # pacbio_recruitment_plots.append(fig.add_subplot(231))
    # pacbio_recruitment_plots.append(fig.add_subplot(232, sharey=pacbio_recruitment_plots[0]))
    # pacbio_recruitment_plots.append(fig.add_subplot(233, sharey=pacbio_recruitment_plots[0]))
    # add_recruitment_results_for_pacbio(pacbio_recruitment_plots, results_dir='../pacbio_coverage_experiment/')

    illumina_recruitment_plots = list([])
    illumina_recruitment_plots.append(fig.add_subplot(131))
    illumina_recruitment_plots.append(fig.add_subplot(132))
    illumina_recruitment_plots.append(fig.add_subplot(133))
    add_recruitment_results_for_illumina(illumina_recruitment_plots, results_dir='../Illumina_copy_number_short_vntrs_mapping/')

    plt.tight_layout(pad=0.6, w_pad=0.5, h_pad=1.0)
    # plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.3, hspace=0.4)
    plt.subplots_adjust(top=0.80, left=0.1, bottom=0.1)

    illumina_handles, illumina_labels = illumina_recruitment_plots[2].get_legend_handles_labels()
    # handles, labels = pacbio_recruitment_plots[2].get_legend_handles_labels()
    # plt.figlegend(handles + illumina_handles[1:], labels + illumina_labels[1:], loc='upper center', ncol=5, labelspacing=0.)
    plt.figlegend(illumina_handles, illumina_labels, loc='upper center', ncol=5, labelspacing=0.)
    # fig.legend(lines, labels, loc=(0.5, 0), ncol=5)

    plt.savefig('read_recruitment_result.pdf', bbox_inches='tight') 
Example 8
Project: frbpoppy   Author: davidgardenier   File: frbpoppy_frbcat.py    MIT License 4 votes vote down vote up
def plot_dists(surv_pop, telescope):
    """Plot the fluence and DM distribution of a surveyed population.

    Args:
        surv_pop (Population): Population from which to plot
        telescope (str): Name of the telescope with which to compare the
            distribution. Necessary for Frbcat.

    """
    plot_aa_style(cols=2)

    # Plot dm distribution
    f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)

    dm_frbpoppy = surv_pop.frbs.dm
    pprint(f'Number of detected FRBs: {len(dm_frbpoppy)}')
    ax1.step(*hist(dm_frbpoppy), where='mid', linestyle='dashed')

    df = Frbcat().df
    dm_frbcat = df[df.telescope == telescope].dm
    ax1.step(*hist(dm_frbcat), where='mid')

    # Compare distributions
    ks = ks_2samp(dm_frbpoppy, dm_frbcat)
    text = fr'$p={round(ks[1], 2)}$'
    anchored_text = AnchoredText(text, loc=1, borderpad=1., frameon=False)
    ax1.add_artist(anchored_text)

    ax1.set_xlabel(r'DM ($\textrm{pc}\ \textrm{cm}^{-3}$)')
    ax1.set_ylabel('Fraction')
    ax1.set_ylim([0, 1.1])
    ax1.set_xlim([0, 3500])

    # Plot fluence distributions
    fluence_frbpoppy = surv_pop.frbs.fluence
    ax2.step(*hist(fluence_frbpoppy, bin_type='log'), where='mid',
             label='frbpoppy', linestyle='dashed')

    fluence_frbcat = df[df.telescope == telescope].fluence
    ax2.step(*hist(fluence_frbcat, bin_type='log'), where='mid',
             label='frbcat')

    # Compare distributions
    ks = ks_2samp(fluence_frbpoppy, fluence_frbcat)
    text = fr'$p={round(ks[1], 2)}$'
    anchored_text = AnchoredText(text, loc=1, borderpad=1., frameon=False)
    ax2.add_artist(anchored_text)

    ax2.set_xlabel(r'Fluence (Jy ms)')
    ax2.set_ylim([0, 1.1])
    ax2.set_xlim([5e-1, 1e4])
    plt.xscale('log')

    plt.figlegend(loc='upper center', ncol=2, framealpha=1)

    plt.tight_layout()
    plt.savefig(rel_path(f'plots/frbpoppy_{telescope}.pdf'))
    plt.clf() 
Example 9
Project: optimal_landing   Author: darioizzo   File: vis.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def compare_control(traj, traj_comp, shadow_last=0,plot_columns = 4, order=None):

    xlabel = 't'
    if 't' in traj:
        t = traj['t']
    else:
        print('Time is needed for control comparison')
        return None

    if 't' in traj_comp:
        t_comp = traj_comp['t']
    else:
        print('Time is needed for control comparison')
        return None

    columns = [c for c in traj.columns if c != 't']
    if not order == None:
        columns = [columns[i] for i in order]

    plot_rows = int(len(columns)/plot_columns)

    if len(columns) % plot_columns > 0:
        plot_rows += 1

    sns.set(font_scale=1.8)
    sns.set_style("whitegrid")
    sns.set_style("ticks", {"xtick.major.size": 4, "ytick.major.size": 4})

    plt.rcParams['figure.figsize'] = (12, 5 *plot_rows)

    fig, axes = plt.subplots(nrows=plot_rows, ncols=plot_columns)
    sns.set_context(font_scale=2)


    for i, c in enumerate(columns):
        bg_color = None
        if i > (len(columns)-shadow_last-1):
            bg_color = 'lightgray'
        plt.subplot(plot_rows, plot_columns, i+1, axisbg=bg_color)
        plt.xlabel(xlabel)
        plt.ylabel(c)
        l1, = plt.plot(t, traj[c])
        l2, = plt.plot(t_comp, traj_comp[c], c=sns.color_palette()[2])
        plt.locator_params(nbins=4)
        r = (max(traj[c])) - (min(traj[c]))
        plt.ylim((min(traj[c])-0.1*r, max(traj[c])+0.1*r))
        plt.xlim((t.iloc[0], t.iloc[-1]))

    plt.figlegend([l1,l2],['Optimal control', 'DNN control'],loc = 'upper center', ncol=2,prop={'size':20}, bbox_to_anchor=(0.5, 1.01 ))

    for i in range(len(columns),plot_rows*plot_columns):
        plt.subplot(plot_rows,plot_columns,i+1)
        plt.axis('off')

    plt.tight_layout()
    return fig 
Example 10
Project: pcay   Author: zpace   File: diagnostics.py    MIT License 4 votes vote down vote up
def make_diag_figure(self, xnames, ynames):
        nobj = len(xnames)

        # initialize subplot size
        gs, fig = ftools.gen_gridspec_fig(
            nobj, add_row=False, border=(0.6, 0.6, 0.2, 0.4),
            space=(0.6, 0.35))

        # set up subplot interactions
        gs_geo = gs.get_geometry()

        fgrid_r, fgrid_c = tuple(list(range(n)) for n in gs_geo)
        gs_iter = iproduct(fgrid_r, fgrid_c)

        # set up kwargs for matplotlib errorbar
        # prefer to change color, then marker
        colors_ = ['C{}'.format(cn) for cn in range(10)]
        markers_ = ['o', 'v', 's', 'P', 'X', 'D', 'H']

        # iterate through rows & columns (rows change fastest)
        # which correspond to different quantities
        for (i, (ri, ci)) in enumerate(gs_iter):

            if i >= len(xnames):
                continue

            # choose axis
            ax = fig.add_subplot(gs[ri, ci])
            kwarg_cycler = cycler(marker=markers_) * \
                           cycler(c=colors_)

            xqty = xnames[i]
            yqty = ynames[i]

            # now iterate through results hdulists
            for (j, (result, kwargs)) in enumerate(
                zip(self.results, kwarg_cycler)):

                kwargs['label'] = result[0].header['PLATEIFU']

                ax = self._add_log_offset_plot(
                    j, xqty=xqty, yqty=yqty, ax=ax, **kwargs)

                ax.tick_params(labelsize=5)

            if i == 0:
                handles_, labels_ = ax.get_legend_handles_labels()
                plt.figlegend(
                    handles=handles_, labels=labels_,
                    loc='upper right', prop={'size': 4.})

        fig.suptitle('PCA fitting diagnostics', size=8.)

        return fig 
Example 11
Project: DSSG19-Cochrane-PUBLIC   Author: alan-turing-institute   File: citations_features_visualization.py    MIT License 4 votes vote down vote up
def plot_citations_features_small_multiples(conn, save_path='/data/figs/eda/citations_histograms.png'):
    """
    Creates a small multiples plot with of plot_citations_histograms().
    Saves file to save_path.

    Parameters
    ==========
    conn : SQLConn class instance
    save_path : str
        Local path where plot should be saved.

    """

    ### Pull data ###
    query = f"""
    select a.*, b.*
    from semantic.papers_rgs_wide a
    left join semantic.citations_avg b
    on a.recordid=b.c_recordid;
    """

    data = conn.query(query)
    data.fillna(0, inplace=True)

    ### Pull labels ###
    bad_cols = ['recordid', 'c_recordid', 'citations_available']
    review_groups = []
    for col in list(data.columns):
        if not col in bad_cols and col[:5] != "cited":
            review_groups.append(col)

    ### Prep plot legend ###
    red_patch = mpatches.Patch(color='firebrick', label='Non-review group paper')
    blue_patch = mpatches.Patch(color='#1f497d', label='Review group paper')

    ### Plot ###
    fig = plt.figure(figsize=(40, 40))
    for i, review_group in enumerate(review_groups):
        plt.subplot(8, 8, i + 1)
        plot_citations_histograms(data=data, review_group=review_group)
    # plt.suptitle('Distribution of proportion of cited papers belonging to that review group', fontsize=50, y=1.05)
    plt.figlegend(handles=[red_patch, blue_patch], loc='lower right', fontsize=30)
    plt.tight_layout()
    plt.savefig(save_path)