Python matplotlib 模块,rc() 实例源码

我们从Python开源项目中,提取了以下26个代码示例,用于说明如何使用matplotlib.rc()

项目:lang-reps    作者:chaitanyamalaviya    | 项目源码 | 文件源码
def plot_sent_trajectories(sents, decode_plot):

    font = {'family' : 'normal',
            'size'   : 14}

    matplotlib.rc('font', **font) 
    i = 0    
    l = ["Portuguese","Catalan"]

    axes = plt.gca()
    #axes.set_xlim([xmin,xmax])
    axes.set_ylim([-1,1])

    for sent, enc in zip(sents, decode_plot):
    if i==2: continue
        i += 1
        #times = np.arange(len(enc))
        times = np.linspace(0,1,len(enc))
        plt.plot(times, enc, label=l[i-1])
    plt.title("Hidden Node Trajectories")
    plt.xlabel('timestep')
    plt.ylabel('trajectories')
    plt.legend(loc='best')
    plt.savefig("final_tests/cr_por_cat_hidden_cell_trajectories", bbox_inches="tight")
    plt.close()
项目:Codes    作者:SP2RC-Coding-Club    | 项目源码 | 文件源码
def density_diagram(disp_rel, K, W, R1, R1min, R1max,
                    just_dots=False):
    # Plot omega/k against rho_1/rho_0 for eigenmodes

    Wmin = sf.cT
    Wmax = sf.vA

    R1_range = np.linspace(R1min, R1max, 51)
    W_range = np.linspace(Wmin, Wmax, 51)

    # Global font change
    font = {'size': 15}
    matplotlib.rc('font', **font)

    plt.figure(num=None, figsize=(10, 11), facecolor='w', edgecolor='k')
    ax = plt.subplot()

    if just_dots == True:
        #Plot the dots
        W_array = tool.point_find(disp_rel, R1_range, W_range,
                                          args=(None))
        ax.plot(R1_range, W_array, '.', color = 'b')
        ax.set_xlim(0, R1_range[-1])
        ax.set_ylim(Wmin, Wmax)
项目:DeepLearning    作者:Wanwannodao    | 项目源码 | 文件源码
def plot(data, index, title='data', x_label='X', y_label='Y'):
    #font = {'family' : 'Helvetica'}
    #matplotlib.rc('font', **font)
    matplotlib.rc('lines', linewidth=2)
    plt.style.use('ggplot')
    df = pd.DataFrame(data, index=index)
    df.plot(title=title, fontsize=13, alpha=0.75, rot=45, figsize=(15, 10))
    plt.xlabel(x_label, fontsize=15)
    plt.ylabel(y_label, fontsize=15)

    plt.savefig("{}.jpg".format(title))


# ====================
# Data Loader 
# ====================
项目:kernel-gof    作者:wittawatj    | 项目源码 | 文件源码
def set_default_matplotlib_options():
    # font options
    font = {
    #     'family' : 'normal',
        #'weight' : 'bold',
        'size'   : 30
    }
    matplotlib.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})


    # matplotlib.use('cairo')
    matplotlib.rc('text', usetex=True)
    matplotlib.rcParams['text.usetex'] = True
    plt.rc('font', **font)
    plt.rc('lines', linewidth=3, markersize=10)
    # matplotlib.rcParams['ps.useafm'] = True
    # matplotlib.rcParams['pdf.use14corefonts'] = True

    matplotlib.rcParams['pdf.fonttype'] = 42
    matplotlib.rcParams['ps.fonttype'] = 42
项目:CS224n    作者:akash9182    | 项目源码 | 文件源码
def make_dynamics_plot(args, x, h, ht_rnn, ht_gru, params):
    matplotlib.rc('text', usetex=True)
    matplotlib.rc('font', family='serif')

    Ur, Wr, br, Uz, Wz, bz, Uo, Wo, bo = params

    plt.clf()
    plt.title("""Cell dynamics when x={}:
Ur={:.2f}, Wr={:.2f}, br={:.2f}
Uz={:.2f}, Wz={:.2f}, bz={:.2f}
Uo={:.2f}, Wo={:.2f}, bo={:.2f}""".format(x, Ur[0,0], Wr[0,0], br[0], Uz[0,0], Wz[0,0], bz[0], Uo[0,0], Wo[0,0], bo[0]))

    plt.plot(h, ht_rnn, label="rnn")
    plt.plot(h, ht_gru, label="gru")
    plt.plot(h, h, color='gray', linestyle='--')
    plt.ylabel("$h_{t}$")
    plt.xlabel("$h_{t-1}$")
    plt.legend()
    output_path = "{}-{}-{}.png".format(args.output_prefix, x, "dynamics")
    plt.savefig(output_path)
项目:tredparse    作者:humanlongevity    | 项目源码 | 文件源码
def savefig(figname, dpi=150, iopts=None, cleanup=True):
    try:
        format = figname.rsplit(".", 1)[-1].lower()
    except:
        format = "pdf"
    try:
        plt.savefig(figname, dpi=dpi, format=format)
    except Exception as e:
        message = "savefig failed. Reset usetex to False."
        message += "\n{0}".format(str(e))
        logging.error(message)
        rc('text', **{'usetex': False})
        plt.savefig(figname, dpi=dpi)

    msg = "Figure saved to `{0}`".format(figname)
    if iopts:
        msg += " {0}".format(iopts)
    logging.debug(msg)

    if cleanup:
        plt.rcdefaults()


# human readable size (Kb, Mb, Gb)
项目:tredparse    作者:humanlongevity    | 项目源码 | 文件源码
def setup_theme(context='notebook', style="darkgrid", palette='deep', font='Helvetica'):
    try:
        import seaborn as sns
        extra_rc = {"lines.linewidth": 1,
                    "lines.markeredgewidth": 1,
                    "patch.edgecolor": 'k',
                    }
        sns.set(context=context, style=style, palette=palette, rc=extra_rc)
    except (ImportError, SyntaxError):
        pass

    rc('text', usetex=True)

    if font == "Helvetica":
        rc('font', **{'family': 'sans-serif', 'sans-serif': ['Helvetica']})
    elif font == "Palatino":
        rc('font', **{'family':'serif','serif': ['Palatino']})
    elif font == "Schoolbook":
        rc('font', **{'family':'serif','serif': ['Century Schoolbook L']})
项目:pybot    作者:spillai    | 项目源码 | 文件源码
def plot_poses(poses, pose_type='absolute'): 

    f = plt.figure(1)
    f.clf()
    f.subplots_adjust(hspace=0.25)

    # , **{'ylabel': 'Position X(m)', 'xlim': [min(xs), max(xs)]}
    pparams = { 'linewidth':1, }
    # font = { 'family': 'normal', 'weight': 'normal', 'size': 12 }
    # mpl.rc('font', **font)

    rpyxyz = np.vstack([pose.to_rpyxyz() for pose in poses])
    ax = f.add_subplot(2, 1, 1)

    if pose_type == 'absolute': 
        for j,label in enumerate(['Roll', 'Pitch', 'Yaw']): 
            ax.plot(np.unwrap(rpyxyz[:,j], discont=np.pi), label=label)
    elif pose_type == 'relative': 
        for j,label in enumerate(['Roll', 'Pitch', 'Yaw']): 
            ax.plot(np.unwrap(rpyxyz[1:,j]-rpyxyz[:-1,j], discont=np.pi), label=label)
    else: 
        raise RuntimeError('Unknown pose_type=%s, use absolute or relative' % pose_type)
    ax.legend(loc='upper right', fancybox=False, ncol=3, 
              # bbox_to_anchor=(1.0,1.2), 
              prop={'size':13})

    ax = f.add_subplot(2, 1, 2)
    for j,label in enumerate(['X', 'Y', 'Z']): 
        ax.plot(rpyxyz[:,j+3], label=label)
    ax.legend(loc='upper right', fancybox=False, ncol=3, 
              # bbox_to_anchor=(1.0,1.2), 
              prop={'size':13})

    plt.tight_layout()
    plt.show(block=True)
项目:Recruit    作者:Weiyanyu    | 项目源码 | 文件源码
def generateImage(self, sourceName, fileName, image_kind):
        matplotlib.rcParams['font.family'] = 'SimHei'           #???????linux?????
        matplotlib.rc('font', **self.FONT)               
        mydata = pd.read_csv(self.FILE_PATH + sourceName)       
        mydata.sort_index()

        if image_kind == 'pie':
            mydata.plot(kind='pie', subplots=True, figsize=(10,10), autopct='%1.1f%%', fontsize=20)
        elif image_kind == 'bar':
            mydata.plot(kind='bar', subplots=True, fontsize=10, figsize=(4,6))
        else:
            raise TypeError('????')

        plt.savefig(self.FILE_PATH + 'images/' + fileName,dpi=100)
        plt.close()
项目:cortex    作者:rdevon    | 项目源码 | 文件源码
def save(self, out_path):
        '''Saves a figure for the monitor

        Args:
            out_path: str
        '''

        plt.clf()
        np.set_printoptions(precision=4)
        font = {
            'size': 7
        }
        matplotlib.rc('font', **font)
        y = 2
        x = ((len(self.d) - 1) // y) + 1
        fig, axes = plt.subplots(y, x)
        fig.set_size_inches(20, 8)

        for j, (k, v) in enumerate(self.d.iteritems()):
            ax = axes[j // x, j % x]
            ax.plot(v, label=k)
            if k in self.d_valid.keys():
                ax.plot(self.d_valid[k], label=k + '(valid)')
            ax.set_title(k)
            ax.legend()

        plt.tight_layout()
        plt.savefig(out_path, facecolor=(1, 1, 1))
        plt.close()
项目:mondrian-kernel    作者:matejbalog    | 项目源码 | 文件源码
def initialize_plotting():
    font = {'family': 'sans-serif', 'sans-serif': ['Helvetica'], 'size': 14}
    matplotlib.rc('font', **font)
    matplotlib.rc('text', usetex=True)
项目:epsilon_free_inference    作者:gpapamak    | 项目源码 | 文件源码
def test_LotkaVolterra(savefile=None):
    """
    Runs and plots a single simulation of the lotka volterra model.
    """

    params = true_params
    #params = sim_prior_params()

    lv = mjp.LotkaVolterra(init, params)
    states = lv.sim_time(dt, duration)
    times = np.linspace(0.0, duration, int(duration / dt) + 1)

    sum_stats = calc_summary_stats(states)
    print sum_stats

    fontsize = 20
    if savefile is not None:
        matplotlib.rcParams.update({'font.size': fontsize})
        matplotlib.rc('text', usetex=True)
        savepath = '../nips_2016/figs/lv/'

    fig = plt.figure()
    plt.plot(times, states[:, 0], lw=3, label='Predators')
    plt.plot(times, states[:, 1], lw=3, label='Prey')
    plt.xlabel('Time')
    plt.ylabel('Population counts')
    plt.ylim([0, 350])
    #plt.title('params = {0}'.format(params))
    plt.legend(loc='upper right', handletextpad=0.5, labelspacing=0.5, borderaxespad=0.5, handlelength=2.0, fontsize=fontsize)
    plt.show(block=False)
    if savefile is not None: fig.savefig(savepath + savefile + '.pdf')
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _check_grid_settings(self, obj, kinds, kws={}):
        # Make sure plot defaults to rcParams['axes.grid'] setting, GH 9792

        import matplotlib as mpl

        def is_grid_on():
            xoff = all(not g.gridOn
                       for g in self.plt.gca().xaxis.get_major_ticks())
            yoff = all(not g.gridOn
                       for g in self.plt.gca().yaxis.get_major_ticks())
            return not (xoff and yoff)

        spndx = 1
        for kind in kinds:
            if not _ok_for_gaussian_kde(kind):
                continue

            self.plt.subplot(1, 4 * len(kinds), spndx)
            spndx += 1
            mpl.rc('axes', grid=False)
            obj.plot(kind=kind, **kws)
            self.assertFalse(is_grid_on())

            self.plt.subplot(1, 4 * len(kinds), spndx)
            spndx += 1
            mpl.rc('axes', grid=True)
            obj.plot(kind=kind, grid=False, **kws)
            self.assertFalse(is_grid_on())

            if kind != 'pie':
                self.plt.subplot(1, 4 * len(kinds), spndx)
                spndx += 1
                mpl.rc('axes', grid=True)
                obj.plot(kind=kind, **kws)
                self.assertTrue(is_grid_on())

                self.plt.subplot(1, 4 * len(kinds), spndx)
                spndx += 1
                mpl.rc('axes', grid=False)
                obj.plot(kind=kind, grid=True, **kws)
                self.assertTrue(is_grid_on())
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def test_rcParams_bar_colors(self):
        import matplotlib as mpl
        color_tuples = [(0.9, 0, 0, 1), (0, 0.9, 0, 1), (0, 0, 0.9, 1)]
        try:  # mpl 1.5
            with mpl.rc_context(
                    rc={'axes.prop_cycle': mpl.cycler("color", color_tuples)}):
                barplot = pd.DataFrame([[1, 2, 3]]).plot(kind="bar")
        except (AttributeError, KeyError):  # mpl 1.4
            with mpl.rc_context(rc={'axes.color_cycle': color_tuples}):
                barplot = pd.DataFrame([[1, 2, 3]]).plot(kind="bar")
        self.assertEqual(color_tuples, [c.get_facecolor()
                                        for c in barplot.patches])
项目:KDDCUP2016    作者:hugochan    | 项目源码 | 文件源码
def cdf(v, title='', 
                xlabel='', ylabel='', 
                xlim=(), ylim=(), 
                xscale='linear', yscale='linear', 
                linewidth=1.5, 
                outfile=None) :

    fs = count(v)
    values, freqs = zip(*sorted(fs.items()))  # Split values and frequencies sorting by the values

    cum  = np.cumsum(freqs, dtype=np.float64)
    cum /= np.sum(freqs)

    pp.clf()

    matplotlib.rc('font', size=24)

    pp.title(title) #, {'fontsize' : 22}
    pp.xlabel(xlabel)
    pp.ylabel(ylabel)
    pp.xscale(xscale)
    pp.yscale(yscale)
    pp.grid()
#   pp.tight_layout(pad=0.2)

#   pp.yscale('log')

    if xlim : pp.xlim(xlim)
    if ylim : pp.ylim(ylim)

    pp.tight_layout(pad=0.10)
    pp.plot(values, cum, lw=linewidth)
#   pp.show()

    if outfile:
        pp.savefig(outfile)
项目:hdidx-eval    作者:hdidx    | 项目源码 | 文件源码
def main(args):
    """ Main entry.
    """
    report_lines = load_report(args.report)
    v_results = parse_report(report_lines)

    font = {'family': 'normal',
            # 'weight': 'bold',
            'size': 16}

    matplotlib.rc('font', **font)

    for i, indexer in zip(range(len(args.indexers)), args.indexers):
        fig = plt.figure(i)
        ax = fig.add_subplot(1, 1, 1)
        ax.hold(True)
        print v_results
        for index, nbits, results in v_results:
            if nbits not in [128, 64, 32, 16, 8]:
                continue
            if index != indexer:
                continue
            X = [r[0] for r in results]
            Y = [r[1] for r in results]
            print np.vstack((X, Y))
            ax.plot(X, Y, label="%d-bit" % (nbits))
            plt.xlabel("$R$")
            plt.ylabel("$recall$")
        ax.hold(False)
        ax.set_xscale("log")
        # pl.legend(loc='lower right')
        plt.legend(loc='upper left')
        plt.savefig(args.figdir + "/%s.png" % indexer)
        plt.savefig(args.figdir + "/%s.eps" % indexer)
    plt.show()
项目:kafe    作者:dsavoiu    | 项目源码 | 文件源码
def _update_rcParams(self):
        '''
        Set matplotlib plotting parameters to those from self.plot_style
        '''
        # Update matplotlib's rcParams with those from plot_style
        mpl.rcParams.update(self.plot_style.rcparams_kw)
        mpl.rc('font', **self.plot_style.rcfont_kw)
项目:Polymers    作者:FracturedRocketSpace    | 项目源码 | 文件源码
def savePlots():
    # Save the plots to file
    # Set font and layout.
    font = {'family' : 'normal',
           'weight' : 'normal',
            'size'   : 25}
    import matplotlib
    matplotlib.rc('font', **font)
    from matplotlib import rcParams
    rcParams.update({'figure.autolayout': True})
    # Save to file
    plt.figure(1)
    plt.savefig('polymers.eps', bbox_inches='tight',  dpi=200)
    plt.figure(2)
    plt.savefig('persistence.eps', bbox_inches='tight',  dpi=200)
    plt.figure(3)
    plt.savefig('popSize.eps', bbox_inches='tight',  dpi=200)
    plt.figure(4)
    plt.savefig('histogram.eps', bbox_inches='tight',  dpi=200)
    plt.figure(5)
    plt.savefig('e2e.eps', bbox_inches='tight',  dpi=200)
    plt.figure(6)
    plt.savefig('Gyradius.eps', bbox_inches='tight',  dpi=200)
    if(c.minEp):
        plt.figure(7)
        plt.savefig('EPmin.eps', bbox_inches='tight',  dpi=200)
    plt.figure(8)
    plt.savefig('e2ePolymers.eps', bbox_inches='tight',  dpi=200)
项目:KMMMs    作者:blt2114    | 项目源码 | 文件源码
def plot_figure(MA0125_true_points, MA0125_fit_points, MA0078_true_points,
                MA0078_fit_points):
    """plot_figure plots the figure comparing the two motifs.

    Args:
        MA0125_true_points: true motif params as np.array
        MA0125_fit_points: fit motif params as np.array
        MA0078_true_points: true motif params as np.array
        MA0078_fit_points: fit motif params as np.array
    """
    ### PLOT FIGURE ###
    font = {'size' : 18}

    matplotlib.rc('font', **font)
    matplotlib.rc('xtick', labelsize=13)
    matplotlib.rc('ytick', labelsize=13)

    f1 = plt.figure(figsize=(13, 6))
    gs1 = gridspec.GridSpec(1, 2)
    gs1.update(wspace=0.025)
    ax1 = plt.subplot(gs1[0])
    ax2 = plt.subplot(gs1[1])

    plot_comparison(ax1, (MA0125_true_points, MA0125_fit_points), "Nobox (MA0125.1)")
    plot_comparison(ax2, (MA0078_true_points, MA0078_fit_points), "Sox-17 (MA0078.1)")
    ax1.set_ylabel('Recovered Parameter')
    plt.setp(ax2.get_yticklabels(), visible=False)
    f1.savefig("2_motifs_synthetic.png",transparent=True)
    plt.show()
项目:tredparse    作者:humanlongevity    | 项目源码 | 文件源码
def set_bedpe(self):
        self.add_option("--norc", dest="rc", default=True, action="store_false",
                     help="Do not reverse complement, expect innie reads")
        self.add_option("--minlen", default=2000, type="int",
                     help="Minimum insert size")
        self.add_option("--maxlen", default=8000, type="int",
                     help="Maximum insert size")
        self.add_option("--dup", default=10, type="int",
                     help="Filter duplicates with coordinates within this distance")
项目:lotss-catalogue    作者:mhardcastle    | 项目源码 | 文件源码
def paper_single(TW = 6.64, AR = 0.74, FF = 1.):
    '''paper_single(TW = 6.64, AR = 0.74, FF = 1.)
    TW = 3.32
    AR = 0.74
    FF = 1.
    #mpl.rc('figure', figsize=(4.5,3.34), dpi=200)
    mpl.rc('figure', figsize=(FF*TW, FF*TW*AR), dpi=200)
    mpl.rc('figure.subplot', left=0.18, right=0.97, bottom=0.18, top=0.9)
    mpl.rc('lines', linewidth=1.0, markersize=4.0)
    mpl.rc('font', size=9.0, family="serif", serif="CM")
    mpl.rc('xtick', labelsize='small')
    mpl.rc('ytick', labelsize='small')
    mpl.rc('axes', linewidth=0.75)
    mpl.rc('legend', fontsize='small', numpoints=1, labelspacing=0.4, frameon=False) 
    mpl.rc('text', usetex=True) 
    mpl.rc('savefig', dpi=300)
    '''
    mpl.rc('figure', figsize=(FF*TW, FF*TW*AR), dpi=100)
    mpl.rc('figure.subplot', left=0.15, right=0.95, bottom=0.15, top=0.92)
    mpl.rc('lines', linewidth=1.75, markersize=8.0, markeredgewidth=0.75)
    mpl.rc('font', size=18.0, family="serif", serif="CM")
    mpl.rc('xtick', labelsize='small')
    mpl.rc('ytick', labelsize='small')
    mpl.rc('xtick.major', width=1.0, size=8)
    mpl.rc('ytick.major', width=1.0, size=8)
    mpl.rc('xtick.minor', width=1.0, size=4)
    mpl.rc('ytick.minor', width=1.0, size=4)
    mpl.rc('axes', linewidth=1.5)
    mpl.rc('legend', fontsize='small', numpoints=1, labelspacing=0.4, frameon=False) 
    mpl.rc('text', usetex=True) 
    mpl.rc('savefig', dpi=300)
项目:lotss-catalogue    作者:mhardcastle    | 项目源码 | 文件源码
def paper_double_mult_ax(nrows=1, ncols=1, setticks=True, **kwargs):
    #import matplotlib as mpl
    paper_single()


    TW = 6.97*2
    AR = 0.74
    FF = 1.
    mpl.rc('figure', figsize=(FF*TW, FF*TW*AR), dpi=200)
    mpl.rc('figure.subplot', left=0.1, right=0.97, bottom=0.1, top=0.97)
    mpl.rc('font', size=24.0, family="serif", serif="CM")

    f, ax = plt.subplots(nrows=nrows, ncols=ncols, **kwargs)
    plt.minorticks_on()
    if setticks:
        ylocator6 = plt.MaxNLocator(5)
        xlocator6 = plt.MaxNLocator(6)
        if len(ax.shape) > 1:
            for axrow in ax:
                for axcol in axrow:
                    axcol.xaxis.set_major_locator(xlocator6)
                    axcol.yaxis.set_major_locator(ylocator6)
        else:
            for axcol in ax:
                axcol.xaxis.set_major_locator(xlocator6)
                axcol.yaxis.set_major_locator(ylocator6)
    return f, ax
项目:epsilon_free_inference    作者:gpapamak    | 项目源码 | 文件源码
def plot_results(save=True):

    lw = 3
    fontsize=22
    savepath = '../nips_2016/figs/blr/'
    matplotlib.rcParams.update({'font.size': fontsize})
    matplotlib.rc('text', usetex=True)

    eps_rej, kls_rej, n_sims_rej, n_samples_rej = helper.load(plotsdir + 'rejection_abc_results.pkl')
    eps_mcm, kls_mcm, n_sims_mcm, n_samples_mcm, acc_rate_mcm = helper.load(plotsdir + 'mcmc_abc_results.pkl')
    eps_smc, kls_smc, n_sims_smc, n_samples_smc = helper.load(plotsdir + 'smc_abc_results.pkl')
    kl_mdn_prior, kl_prior_prop, kl_mdn_prop, n_sims_mdn_prior, n_sims_prior_prop, n_sims_mdn_prop = helper.load(plotsdir + 'mdn_abc_results.pkl')

    # plot kl vs eps
    fig, ax = plt.subplots(1, 1)
    ax.loglog(eps_rej, kls_rej, lw=lw, label='Rej.~ABC')
    ax.loglog(eps_mcm, kls_mcm, lw=lw, label='MCMC-ABC')
    ax.loglog(eps_smc, kls_smc, lw=lw, label='SMC-ABC')
    ax.loglog(ax.get_xlim(), [kl_mdn_prior]*2, lw=lw, label='MDN with prior')
    ax.loglog(ax.get_xlim(), [kl_prior_prop]*2, lw=lw, label='Proposal prior')
    ax.loglog(ax.get_xlim(), [kl_mdn_prop]*2, lw=lw, label='MDN with prop.')
    ax.set_xlabel(r'$\epsilon$', labelpad=-1.0)
    ax.set_ylabel('KL divergence')
    ax.set_ylim([10**-2, 0.3*10**4])
    ax.legend(ncol=2, loc='upper left', columnspacing=0.3, handletextpad=0.05, labelspacing=0.3, borderaxespad=0.3, handlelength=1.5, fontsize=fontsize)
    fig.subplots_adjust(bottom=0.11)
    if save: fig.savefig(savepath + 'kl_vs_eps.pdf')

    # plot number of simulations vs kl
    fig, ax = plt.subplots(1, 1)
    ax.loglog(kls_rej, n_sims_rej / n_samples_rej, lw=lw, label='Rej.~ABC')
    ax.loglog(kls_mcm, n_sims_mcm / n_samples_mcm, lw=lw, label='MCMC-ABC')
    ax.loglog(kls_smc, n_sims_smc / n_samples_smc, lw=lw, label='SMC-ABC')
    ax.loglog(kl_mdn_prior, n_sims_mdn_prior, 'o', ms=8, label='MDN with prior')
    ax.loglog(kl_prior_prop, n_sims_prior_prop, 'o', ms=8, label='Proposal prior')
    ax.loglog(kl_mdn_prop, n_sims_mdn_prop, 'o', ms=8, label='MDN with prop.')
    ax.set_xlabel('KL divergence', labelpad=-1.0)
    ax.set_ylabel('\# simulations (per effective sample for ABC)')
    ax.set_xlim([10**-2, 10**4])
    ax.legend(loc='upper right', columnspacing=0.3, handletextpad=0.4, labelspacing=0.3, borderaxespad=0.3, numpoints=1, handlelength=1.0, fontsize=fontsize)
    fig.subplots_adjust(bottom=0.11)
    if save: fig.savefig(savepath + 'sims_vs_kl.pdf')

    plt.show(block=False)
项目:kafe    作者:dsavoiu    | 项目源码 | 文件源码
def __init__(self):
        '''
        Construct a default plot style.
        '''

        # Define a progression of matplotlib
        # marker and line styles, as well as colors
        self.markers = ['o', '^', 's', 'D', 'v', 'h', '*', '+', 'x']
        self.lines = ['-', '--', '-.', ':']
        self.markercolors = ['r', 'b', 'g', 'c', 'm', 'k']
        self.linecolors = ['r', 'b', 'g', 'c', 'm', 'k']

        # Define a progression of point sizes
        self.pointsizes = [7]

        # Set other style properties
        self.labelsize = 12     # make labels large
        self.grid = True        # use a grid per default
        self.usetex = True      # tell matplotlib to use TeX

        # Some default styles and offsets
        self.axis_label_styles = ('italic', 'italic')
        self.axis_label_align = ('right', 'right')
        #self.axis_label_coords = ((.5, -.1), (-.12, .5))
        self.axis_label_coords = ((1.02, -.1), (-.12, 1.02))
        self.axis_label_pad = (7, 7)

        # Set legend parameters
        self.legendparams_kw = {
            'ncol': 1,
            #'fancybox': True,
            'shadow': False,
            'numpoints': 1,
            'bbox_to_anchor': (1.05, 1.),
            'borderaxespad': 0.,
            #'borderpad': 0.05
        }

        # Default keyword arguments to pass to rc('font',...)
        self.rcfont_kw = {
            'family': 'sans-serif',
            'serif':  ['Palatino', 'cm', 'CMU Classical Serif'],
            'sans-serif':  ['Helvetica', 'CMU Bright'],
            'monospace':  ['Monospace', 'CMU Typewriter Text']
        }
        self.rcparams_kw = {
            'axes.labelsize': 20,
            'font.size': 14,
            'legend.fontsize': 18,
            'xtick.labelsize': 20,
            'ytick.labelsize': 20,
            'text.usetex': True,
            #'text.latex.preamble': [r"\usepackage{sansmath}"],
            'axes.unicode_minus': True,
            #'legend.loc': 'best',
            'legend.loc': 'upper left',
            'figure.figsize': (12, 6)
        }
项目:formulas    作者:jzuhone    | 项目源码 | 文件源码
def quick_plot(self, x_min, x_max, x_scale="linear", y_scale="linear",
                   res=200, filename=None, function_name="f", units=None): # pragma: no cover
        """
        Plot the formula.

        Parameters
        ----------
        x_min : unitful scalar quantity
            The mininum value of the "x" variable to plot.
        x_max : unitful scalar quantity
            The maximum value of the "x" variable to plot.
        x_scale : string
            The scaling for the x axis. Can be "linear" or "log".
        y_scale : string
            The scaling for the y axis. Can be "linear" or "log".
        res : integer
            The number of points to use in the plot. Default is 200.
        filename : str
            If set, save the plot to this filename.
        function_name : str
            The name of the function for the y-axis of the plot.
        units : str
            The units to convert the y-axis values to.

        Examples
        --------
        >>> import astropy.units as u
        >>> r_min = 0.1*u.kpc
        >>> r_max = 1000.*u.kpc
        >>> density_profile.quick_plot(r_min, r_max, x_scale="log")
        """
        from IPython.display import HTML, display
        matplotlib.rc("font", size=16, family="serif")
        fig = matplotlib.figure.Figure(figsize=(8,8))
        ax = fig.add_subplot(111)
        arr = check_type(x_min)
        x = arr(np.linspace(x_min.value, x_max.value, num=res), get_units(x_min))
        y = arr(self(x))
        if units is not None:
            y = in_units(y, units)
        x_units = latexify_units(x)
        y_units = latexify_units(y)
        ax.plot(np.array(x), np.array(y))
        ax.set_xlabel(r"$\mathrm{%s}$ (" % self.x + x_units + ")")
        ax.set_ylabel(r"$\mathrm{%s(%s)}$ (" % (function_name, self.x) + y_units + ")")
        ax.set_xscale(x_scale)
        ax.set_yscale(y_scale)
        fig.tight_layout()
        if filename is not None:
            fig.savefig(filename)
        canvas = FigureCanvasAgg(fig)
        f = BytesIO()
        canvas.print_figure(f)
        f.seek(0)
        img = base64.b64encode(f.read()).decode()
        ret = r'<img style="max-width:100%%;max-height:100%%;" ' \
              r'src="data:image/png;base64,{0}"><br>'.format(img)
        display(HTML(ret))
项目:turbo_seti    作者:UCBerkeleySETI    | 项目源码 | 文件源码
def plot_waterfall(fil, f_start=None, f_stop=None, if_id=0, logged=True,cb=False,freq_label=False,MJD_time=False, **kwargs):
    """ Plot waterfall of data

    Args:
        f_start (float): start frequency, in MHz
        f_stop (float): stop frequency, in MHz
        logged (bool): Plot in linear (False) or dB units (True),
        cb (bool): for plotting the colorbar
        kwargs: keyword args to be passed to matplotlib imshow()
    """

    matplotlib.rc('font', **font)

    plot_f, plot_data = fil.grab_data(f_start, f_stop, if_id)

    # Make sure waterfall plot is under 4k*4k
    dec_fac_x, dec_fac_y = 1, 1
    if plot_data.shape[0] > MAX_IMSHOW_POINTS[0]:
        dec_fac_x = plot_data.shape[0] / MAX_IMSHOW_POINTS[0]

    if plot_data.shape[1] > MAX_IMSHOW_POINTS[1]:
        dec_fac_y =  plot_data.shape[1] /  MAX_IMSHOW_POINTS[1]

    plot_data = rebin(plot_data, dec_fac_x, dec_fac_y)

    if MJD_time:
        extent=(plot_f[0], plot_f[-1], fil.timestamps[-1], fil.timestamps[0])
    else:
        extent=(plot_f[0], plot_f[-1], (fil.timestamps[-1]-fil.timestamps[0])*24.*60.*60, 0.0)

    this_plot = plt.imshow(plot_data,
        aspect='auto',
        rasterized=True,
        interpolation='nearest',
        extent=extent,
        cmap='viridis_r',
        **kwargs
    )
    if cb:
        plt.colorbar()

    if freq_label:
        plt.xlabel("Frequency [Hz]",fontdict=font)
    if MJD_time:
        plt.ylabel("Time [MJD]",fontdict=font)
    else:
        plt.ylabel("Time [s]",fontdict=font)

    return this_plot