当前位置: 首页>>代码示例>>Python>>正文


Python Figure.savefig方法代码示例

本文整理汇总了Python中matplotlib.figure.Figure.savefig方法的典型用法代码示例。如果您正苦于以下问题:Python Figure.savefig方法的具体用法?Python Figure.savefig怎么用?Python Figure.savefig使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在matplotlib.figure.Figure的用法示例。


在下文中一共展示了Figure.savefig方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: plot_tdc_event

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import savefig [as 别名]
def plot_tdc_event(points, filename=None):
    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(111, projection='3d')
    xs = points[:, 0]
    ys = points[:, 1]
    zs = points[:, 2]
    cs = points[:, 3]

    p = ax.scatter(xs, ys, zs, c=cs, s=points[:, 3] ** (2) / 5., marker='o')

    ax.set_xlabel('x [250 um]')
    ax.set_ylabel('y [50 um]')
    ax.set_zlabel('t [25 ns]')
    ax.title('Track of one TPC event')
    ax.set_xlim(0, 80)
    ax.set_ylim(0, 336)

    c_bar = fig.colorbar(p)
    c_bar.set_label('charge [TOT]')

    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    elif filename:
        fig.savefig(filename)
    return fig
开发者ID:liuhb08,项目名称:pyBAR,代码行数:30,代码来源:plotting.py

示例2: test_repeated_save_with_alpha

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import savefig [as 别名]
def test_repeated_save_with_alpha():
    # We want an image which has a background color of bluish green, with an
    # alpha of 0.25.

    fig = Figure([1, 0.4])
    fig.set_facecolor((0, 1, 0.4))
    fig.patch.set_alpha(0.25)

    # The target color is fig.patch.get_facecolor()

    buf = io.BytesIO()

    fig.savefig(buf,
                facecolor=fig.get_facecolor(),
                edgecolor='none')

    # Save the figure again to check that the
    # colors don't bleed from the previous renderer.
    buf.seek(0)
    fig.savefig(buf,
                facecolor=fig.get_facecolor(),
                edgecolor='none')

    # Check the first pixel has the desired color & alpha
    # (approx: 0, 1.0, 0.4, 0.25)
    buf.seek(0)
    assert_array_almost_equal(tuple(imread(buf)[0, 0]),
                              (0.0, 1.0, 0.4, 0.250),
                              decimal=3)
开发者ID:anntzer,项目名称:matplotlib,代码行数:31,代码来源:test_agg.py

示例3: tBidBax_kd

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import savefig [as 别名]
def tBidBax_kd(mcmc_set):
    """ .. todo:: document the basis for this"""
    num_kds = 10000
    # Get indices for the tBid/Bax binding constants
    estimate_params = mcmc = mcmc_set.chains[0].options.estimate_params
    tBid_iBax_kf_index = None
    tBid_iBax_kr_index = None
    for i, p in enumerate(estimate_params):
        if p.name == 'tBid_iBax_kf':
            tBid_iBax_kf_index = i
        elif p.name == 'tBid_iBax_kr':
            tBid_iBax_kr_index = i
    # If we couldn't find the parameters, return None for the result
    if tBid_iBax_kf_index is None or tBid_iBax_kr_index is None:
        return Result(None, None)
    # Sample the kr/kf ratio across the pooled chains
    kd_dist = np.zeros(num_kds)
    for i in range(num_kds):
        position = mcmc_set.get_sample_position()
        kd_dist[i] = ((10 ** position[tBid_iBax_kr_index]) /
                      (10 ** position[tBid_iBax_kf_index]))
    # Calculate the mean and variance
    mean = kd_dist.mean()
    sd = kd_dist.std()

    # Plot the Kd distribution
    plot_filename = '%s_tBidiBax_kd_dist.png' % mcmc_set.name
    fig = Figure()
    ax = fig.gca()
    ax.hist(kd_dist)
    canvas = FigureCanvasAgg(fig)
    fig.set_canvas(canvas)
    fig.savefig(plot_filename)

    return MeanSdResult(mean, sd, plot_filename)
开发者ID:johnbachman,项目名称:tBidBaxLipo,代码行数:37,代码来源:knowledge.py

示例4: write_figures

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import savefig [as 别名]
def write_figures(prefix, directory, dose_name, dose_data, data, ec50_coeffs, feature_set, log_transform):
    """Write out figure scripts for each measurement
    
    prefix - prefix for file names
    directory - write files into this directory
    dose_name - name of the dose measurement
    dose_data - doses per image
    data - data per image
    ec50_coeffs - coefficients calculated by calculate_ec50
    feature_set - tuples of object name and feature name in same order as data
    log_transform - true to log-transform the dose data
    """
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_pdf import FigureCanvasPdf

    if log_transform:
        dose_data = np.log(dose_data)
    for i, (object_name, feature_name) in enumerate(feature_set):
        fdata = data[:, i]
        fcoeffs = ec50_coeffs[i, :]
        filename = "%s%s_%s.pdf" % (prefix, object_name, feature_name)
        pathname = os.path.join(directory, filename)
        f = Figure()
        canvas = FigureCanvasPdf(f)
        ax = f.add_subplot(1, 1, 1)
        x = np.linspace(0, np.max(dose_data), num=100)
        y = sigmoid(fcoeffs, x)
        ax.plot(x, y)
        dose_y = sigmoid(fcoeffs, dose_data)
        ax.plot(dose_data, dose_y, "o")
        ax.set_xlabel("Dose")
        ax.set_ylabel("Response")
        ax.set_title("%s_%s" % (object_name, feature_name))
        f.savefig(pathname)
开发者ID:sanuj,项目名称:CellProfiler,代码行数:36,代码来源:calculatestatistics.py

示例5: acf_of_ml_residuals

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import savefig [as 别名]
def acf_of_ml_residuals(mcmc_set):
    # Get the maximum likelihood parameters
    try:
        (max_likelihood, max_likelihood_position) = mcmc_set.maximum_likelihood()
    except NoPositionsException as npe:
        return Result(None, None)

    # Get the residuals
    residuals = mcmc_set.chains[0].get_residuals(max_likelihood_position)

    # Plot the autocorrelation function
    acf = np.correlate(residuals[1], residuals[1], mode='full')

    plot_filename = '%s_acf_of_ml_residuals.png' % mcmc_set.name
    thumbnail_filename = '%s_acf_of_ml_residuals_th.png' % mcmc_set.name
    fig = Figure()
    ax = fig.gca()
    ax.plot(acf)
    ax.set_title('Autocorrelation of Maximum Likelihood Residuals')

    canvas = FigureCanvasAgg(fig)
    fig.set_canvas(canvas)
    fig.savefig(plot_filename)
    fig.savefig(thumbnail_filename, dpi=10)

    return ThumbnailResult(thumbnail_filename, plot_filename)
开发者ID:johnbachman,项目名称:tBidBaxLipo,代码行数:28,代码来源:residuals.py

示例6: save_as_plt

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import savefig [as 别名]
    def save_as_plt(self, fname, pixel_array=None, vmin=None, vmax=None,
        cmap=None, format=None, origin=None):
        """ This method saves the image from a numpy array using matplotlib

        :param fname: Location and name of the image file to be saved.
        :param pixel_array: Numpy pixel array, i.e. ``numpy()`` return value
        :param vmin: matplotlib vmin
        :param vmax: matplotlib vmax
        :param cmap: matplotlib color map
        :param format: matplotlib format
        :param origin: matplotlib origin

        This method will return True if successful
        """
        from matplotlib.backends.backend_agg \
        import FigureCanvasAgg as FigureCanvas
        from matplotlib.figure import Figure
        from pylab import cm

        if pixel_array is None:
            pixel_array = self.numpy()

        if cmap is None:
            cmap = cm.bone
        fig = Figure(figsize=pixel_array.shape[::-1], dpi=1, frameon=False)
        canvas = FigureCanvas(fig)
        fig.figimage(pixel_array, cmap=cmap, vmin=vmin,
            vmax=vmax, origin=origin)
        fig.savefig(fname, dpi=1, format=format)
        return True
开发者ID:rmsouza01,项目名称:mudicom,代码行数:32,代码来源:image.py

示例7: barChart

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import savefig [as 别名]
def barChart(size, data, output):
    d = data['x']
    ind = np.arange(len(d))
    ys = data['y']

    width = 0.60
    fig = Figure(figsize=(size[0], size[1]), dpi=size[2])
    FigureCanvas(fig)  # Stores canvas on fig.canvas

    axis = fig.add_subplot(111)
    axis.grid(color='r', linestyle='dotted', linewidth=0.1, alpha=0.5)

    bottom = np.zeros(len(ys[0]['data']))
    for y in ys:
        axis.bar(ind, y['data'], width, bottom=bottom, label=y.get('label'))
        bottom += np.array(y['data'])

    axis.set_title(data.get('title', ''))
    axis.set_xlabel(data['xlabel'])
    axis.set_ylabel(data['ylabel'])

    if data.get('allTicks', True) is True:
        axis.set_xticks(ind)

    if 'xtickFnc' in data:
        axis.set_xticklabels([data['xtickFnc'](v) for v in axis.get_xticks()])

    axis.legend()

    fig.savefig(output, format='png', transparent=True)
开发者ID:dkmstr,项目名称:openuds,代码行数:32,代码来源:graphs.py

示例8: plotThreeWay

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import savefig [as 别名]
def plotThreeWay(hist, title, filename=None, x_axis_title=None, minimum=None, maximum=None, bins=101):  # the famous 3 way plot (enhanced)
    if minimum is None:
        minimum = 0
    elif minimum == 'minimum':
        minimum = np.ma.min(hist)
    if maximum == 'median' or maximum is None:
        median = np.ma.median(hist)
        maximum = median * 2  # round_to_multiple(median * 2, math.floor(math.log10(median * 2)))
    elif maximum == 'maximum':
        maximum = np.ma.max(hist)
        maximum = maximum  # round_to_multiple(maximum, math.floor(math.log10(maximum)))
    if maximum < 1 or hist.all() is np.ma.masked:
        maximum = 1

    x_axis_title = '' if x_axis_title is None else x_axis_title
    fig = Figure()
    FigureCanvas(fig)
    fig.patch.set_facecolor('white')
    ax1 = fig.add_subplot(311)
    create_2d_pixel_hist(fig, ax1, hist, title=title, x_axis_title="column", y_axis_title="row", z_min=minimum if minimum else 0, z_max=maximum)
    ax2 = fig.add_subplot(312)
    create_1d_hist(fig, ax2, hist, bins=bins, x_axis_title=x_axis_title, y_axis_title="#", x_min=minimum, x_max=maximum)
    ax3 = fig.add_subplot(313)
    create_pixel_scatter_plot(fig, ax3, hist, x_axis_title="channel=row + column*336", y_axis_title=x_axis_title, y_min=minimum, y_max=maximum)
    fig.tight_layout()
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
开发者ID:liuhb08,项目名称:pyBAR,代码行数:33,代码来源:plotting.py

示例9: plot_correlations

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import savefig [as 别名]
def plot_correlations(filenames, limit=None):
    DataFrame = pd.DataFrame()
    index = 0
    for fileName in filenames:
        with pd.get_store(fileName, 'r') as store:
            tempDataFrame = pd.DataFrame({'Event': store.Hits.Event[:15000], 'Row' + str(index): store.Hits.Row[:15000]})
            tempDataFrame = tempDataFrame.set_index('Event')
            DataFrame = tempDataFrame.join(DataFrame)
            DataFrame = DataFrame.dropna()
            index += 1
            del tempDataFrame
    DataFrame["index"] = DataFrame.index
    DataFrame.drop_duplicates(take_last=True, inplace=True)
    del DataFrame["index"]
    correlationNames = ('Row')
    index = 0
    for corName in correlationNames:
        for colName in itertools.permutations(DataFrame.filter(regex=corName), 2):
            if(corName == 'Col'):
                heatmap, xedges, yedges = np.histogram2d(DataFrame[colName[0]], DataFrame[colName[1]], bins=(80, 80), range=[[1, 80], [1, 80]])
            else:
                heatmap, xedges, yedges = np.histogram2d(DataFrame[colName[0]], DataFrame[colName[1]], bins=(336, 336), range=[[1, 336], [1, 336]])
            extent = [yedges[0] - 0.5, yedges[-1] + 0.5, xedges[-1] + 0.5, xedges[0] - 0.5]
            cmap = cm.get_cmap('hot', 40)
            fig = Figure()
            FigureCanvas(fig)
            ax = fig.add_subplot(111)
            ax.imshow(heatmap, extent=extent, cmap=cmap, interpolation='nearest')
            ax.invert_yaxis()
            ax.set_xlabel(colName[0])
            ax.set_ylabel(colName[1])
            ax.set_title('Correlation plot(' + corName + ')')
            fig.savefig(colName[0] + '_' + colName[1] + '.pdf')
            index += 1
开发者ID:liuhb08,项目名称:pyBAR,代码行数:36,代码来源:plotting.py

示例10: plot_cluster_tot_size

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import savefig [as 别名]
def plot_cluster_tot_size(hist, median=False, z_max=None, filename=None):
    H = hist[0:50, 0:20]
    if z_max is None:
        z_max = np.ma.max(H)
    if z_max < 1 or H.all() is np.ma.masked:
        z_max = 1
    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(111)
    extent = [-0.5, 20.5, 49.5, -0.5]
    bounds = np.linspace(start=0, stop=z_max, num=255, endpoint=True)
    cmap = cm.get_cmap('jet')
    cmap.set_bad('w')
    norm = colors.BoundaryNorm(bounds, cmap.N)
    im = ax.imshow(H, aspect="auto", interpolation='nearest', cmap=cmap, norm=norm, extent=extent)  # for monitoring
    ax.set_title('Cluster size and cluster ToT (' + str(np.sum(H) / 2) + ' entries)')
    ax.set_xlabel('cluster size')
    ax.set_ylabel('cluster ToT')

    ax.invert_yaxis()
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.1)
    cb = fig.colorbar(im, cax=cax, ticks=np.linspace(start=0, stop=z_max, num=9, endpoint=True))
    cb.set_label("#")
    fig.patch.set_facecolor('white')
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
开发者ID:liuhb08,项目名称:pyBAR,代码行数:33,代码来源:plotting.py

示例11: plot_1d_hist

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import savefig [as 别名]
def plot_1d_hist(hist, yerr=None, title=None, x_axis_title=None, y_axis_title=None, x_ticks=None, color='r', plot_range=None, log_y=False, filename=None, figure_name=None):
    logging.info('Plot 1d histogram%s', (': ' + title) if title is not None else '')
    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(111)
    if plot_range is None:
        plot_range = range(0, len(hist))
    if not plot_range:
        plot_range = [0]
    if yerr is not None:
        ax.bar(left=plot_range, height=hist[plot_range], color=color, align='center', yerr=yerr)
    else:
        ax.bar(left=plot_range, height=hist[plot_range], color=color, align='center')
    ax.set_xlim((min(plot_range) - 0.5, max(plot_range) + 0.5))
    ax.set_title(title)
    if x_axis_title is not None:
        ax.set_xlabel(x_axis_title)
    if y_axis_title is not None:
        ax.set_ylabel(y_axis_title)
    if x_ticks is not None:
        ax.set_xticks(range(0, len(hist[:])) if plot_range is None else plot_range)
        ax.set_xticklabels(x_ticks)
        ax.tick_params(which='both', labelsize=8)
    if np.allclose(hist, 0.0):
        ax.set_ylim((0, 1))
    else:
        if log_y:
            ax.set_yscale('log')
    ax.grid(True)
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
开发者ID:liuhb08,项目名称:pyBAR,代码行数:37,代码来源:plotting.py

示例12: plot_scatter_time

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import savefig [as 别名]
def plot_scatter_time(x, y, yerr=None, title=None, legend=None, plot_range=None, plot_range_y=None, x_label=None, y_label=None, marker_style='-o', log_x=False, log_y=False, filename=None):
    logging.info("Plot time scatter plot %s", (': ' + title) if title is not None else '')
    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(111)
    ax.format_xdata = mdates.DateFormatter('%Y-%m-%d')
    times = []
    for time in x:
        times.append(datetime.fromtimestamp(time))
    if yerr is not None:
        ax.errorbar(times, y, yerr=[yerr, yerr], fmt=marker_style)
    else:
        ax.plot(times, y, marker_style)
    ax.set_title(title)
    if x_label is not None:
        ax.set_xlabel(x_label)
    if y_label is not None:
        ax.set_ylabel(y_label)
    if log_x:
        ax.xscale('log')
    if log_y:
        ax.yscale('log')
    if plot_range:
        ax.set_xlim((min(plot_range), max(plot_range)))
    if plot_range_y:
        ax.set_ylim((min(plot_range_y), max(plot_range_y)))
    if legend:
        ax.legend(legend, 0)
    ax.grid(True)
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
开发者ID:liuhb08,项目名称:pyBAR,代码行数:37,代码来源:plotting.py

示例13: plot_correlation

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import savefig [as 别名]
def plot_correlation(hist, title="Hit correlation", xlabel=None, ylabel=None, filename=None):
    logging.info("Plotting correlations")
    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(1, 1, 1)
    cmap = cm.get_cmap('jet')
    extent = [hist[2][0] - 0.5, hist[2][-1] + 0.5, hist[1][-1] + 0.5, hist[1][0] - 0.5]
    ax.set_title(title)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    im = ax.imshow(hist[0], extent=extent, cmap=cmap, interpolation='nearest')
    ax.invert_yaxis()
    # add colorbar
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    z_max = np.max(hist[0])
    bounds = np.linspace(start=0, stop=z_max, num=255, endpoint=True)
    norm = colors.BoundaryNorm(bounds, cmap.N)
    fig.colorbar(im, boundaries=bounds, cmap=cmap, norm=norm, ticks=np.linspace(start=0, stop=z_max, num=9, endpoint=True), cax=cax)
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
开发者ID:liuhb08,项目名称:pyBAR,代码行数:27,代码来源:plotting.py

示例14: plot_scatter

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import savefig [as 别名]
def plot_scatter(x, y, x_err=None, y_err=None, title=None, legend=None, plot_range=None, plot_range_y=None, x_label=None, y_label=None, marker_style='-o', log_x=False, log_y=False, filename=None):
    logging.info('Plot scatter plot %s', (': ' + title) if title is not None else '')
    fig = Figure()
    FigureCanvas(fig)
    ax = fig.add_subplot(111)
    if x_err is not None:
        x_err = [x_err, x_err]
    if y_err is not None:
        y_err = [y_err, y_err]
    if x_err is not None or y_err is not None:
        ax.errorbar(x, y, xerr=x_err, yerr=y_err, fmt=marker_style)
    else:
        ax.plot(x, y, marker_style, markersize=1)
    ax.set_title(title)
    if x_label is not None:
        ax.set_xlabel(x_label)
    if y_label is not None:
        ax.set_ylabel(y_label)
    if log_x:
        ax.set_xscale('log')
    if log_y:
        ax.set_yscale('log')
    if plot_range:
        ax.set_xlim((min(plot_range), max(plot_range)))
    if plot_range_y:
        ax.set_ylim((min(plot_range_y), max(plot_range_y)))
    if legend:
        ax.legend(legend, 0)
    ax.grid(True)
    if not filename:
        fig.show()
    elif isinstance(filename, PdfPages):
        filename.savefig(fig)
    else:
        fig.savefig(filename)
开发者ID:liuhb08,项目名称:pyBAR,代码行数:37,代码来源:plotting.py

示例15: plotBatchResults

# 需要导入模块: from matplotlib.figure import Figure [as 别名]
# 或者: from matplotlib.figure.Figure import savefig [as 别名]
def plotBatchResults(db):
	'Hook called from woo.batch.writeResults'

	import re,math,woo.batch,os
	results=woo.batch.dbReadResults(db)
	out='%s.pdf'%re.sub('\.sqlite$','',db)
	from matplotlib.figure import Figure
	from matplotlib.backends.backend_agg import FigureCanvasAgg
	fig=Figure();
	canvas=FigureCanvasAgg(fig)
	ax1=fig.add_subplot(2,1,1)
	ax2=fig.add_subplot(2,1,2)
	ax1.set_xlabel('Time [s]')
	ax1.set_ylabel('Kinetic energy [J]')
	ax1.grid(True)
	ax2.set_xlabel('Time [s]')
	ax2.set_ylabel('Relative energy error')
	ax2.grid(True)
	for res in results:
		series=res['series']
		pre=res['pre']
		if not res['title']: res['title']=res['sceneId']
		ax1.plot(series['t'],series['kinetic'],label=res['title'],alpha=.6)
		ax2.plot(series['t'],series['relErr'],label=res['title'],alpha=.6)
	for ax,loc in (ax1,'lower left'),(ax2,'lower right'):
		l=ax.legend(loc=loc,labelspacing=.2,prop={'size':7})
		l.get_frame().set_alpha(.4)
	fig.savefig(out)
	print 'Batch figure saved to file://%s'%os.path.abspath(out)
开发者ID:Azeko2xo,项目名称:woodem,代码行数:31,代码来源:horse.py


注:本文中的matplotlib.figure.Figure.savefig方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。