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


Python pyplot.gcf函数代码示例

本文整理汇总了Python中matplotlib.pyplot.gcf函数的典型用法代码示例。如果您正苦于以下问题:Python gcf函数的具体用法?Python gcf怎么用?Python gcf使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: plot

    def plot(self,plot_id):
        device_id = sEtting.device_id #"LASS-Example0"
        if self.first:
            self.init()
            plt.title(sEtting.mqtt_topic + ' Sensor data')
            plt.ylabel('Sensor value')
            plt.xlabel("Data sensing time")

        if plot_id>0:
            #FIXME error handler
            if device_id in dEvices.devs:
                x, y = dEvices.devs[device_id].get_values(sEtting.plot_cnt,plot_id)
                self.first=0
            else:
                print("plot device:" + device_id + " not exist!")
                return
        else:
            x, y = dEvices.get_values(sEtting.plot_cnt) #FIXME
            self.first=0
            # draw and show it
            #self.fig.canvas.draw()
            #plt.show(block=False)

        if len(x)<=0 or not x :
            print("data count=0, ignore plot. Maybe device id is wrong")
        plt.gcf().autofmt_xdate()
        (self.li, )= self.ax.plot(x, y)
        self.li.set_xdata(x)
        self.li.set_ydata(y)
        self.fig.canvas.draw()
        if sEtting.plot_save:
            plt.savefig("lass_" + str(plot_id) + ".png")
        else:
            plt.show(block=False)
开发者ID:wjmuse,项目名称:LASS,代码行数:34,代码来源:lass.py

示例2: plot_jobs_by_skills

def plot_jobs_by_skills(cur, skills):

    skill_jobs = {}
    
    for skill in skills:
        cur.execute('''select count(j.id) amount from jobs j where j.id in
                    (select js.job_id from job_skills js where js.skill=?)''',
                    (skill,))
        res = cur.fetchone()
        skill_jobs[skill] = res[0]
    
    sorted_skill_jobs = zip(*sorted(skill_jobs.items(),
                            key=operator.itemgetter(1), reverse=False))

    fig = plt.figure()
    
    y_pos = np.arange(len(skill_jobs))
    print y_pos
    
    ax = plt.barh(y_pos, sorted_skill_jobs[1], align='center', alpha=0.3)
    plt.yticks(y_pos, ['\n'.join(wrap(x, 10)) for x in sorted_skill_jobs[0]])
    plt.ylabel('Skill')
    plt.xlabel('Amount of jobs')
    autolabel_h(ax)
    
    plt.gcf().subplots_adjust(left=0.20)
    
    return fig
开发者ID:mdmitr,项目名称:upworkStat,代码行数:28,代码来源:create_plots.py

示例3: toggle_artist

 def toggle_artist(self, artist):
     try:
         visible = artist.get_visible()
         artist.set_visible(not visible)
         plt.gcf().canvas.draw()
     except Exception:
         pass
开发者ID:Web5design,项目名称:mtools,代码行数:7,代码来源:mplotqueries.py

示例4: createHistogram

def createHistogram(df, pic, bins=45, rates=False):
    data=mergeMatrix(df, pic)
    matrix=sortMatrix(df, pic)


    density = gaussian_kde(data)
    xs = np.linspace(min(data), max(data), max(data))
    density.covariance_factor = lambda : .25
    density._compute_covariance()
    #xs = np.linspace(min(data), max(data), 1000)

    fig,ax1 = plt.subplots()
    #plt.xlim([0, 4000])
    plt.hist(data, bins=bins, range=[-500, 4000], histtype='stepfilled', color='grey', alpha=0.5)
    lims = plt.ylim()
    height=lims[1]-2
    for i in range(0,len(matrix)):
        currentRow = matrix[i][np.nonzero(matrix[i])]
        plt.plot(currentRow, np.ones(len(currentRow))*height, '|', color='black')
        height -= 2

    plt.axvline(x=0, color='red', linestyle='dashed')
    #plt.axvline(x=1000, color='black', linestyle='dashed')
    #plt.axvline(x=2000, color='black', linestyle='dashed')
    #plt.axvline(x=3000, color='black', linestyle='dashed')

    if rates:
        rates = get_rate(df, pic)
        ax1.text(-250, 4, str(rates[0]), size=15, ha='center', va='center', color='green')
        ax1.text(500, 4, str(rates[1]), size=15, ha='center', va='center', color='green')
        ax1.text(1500, 4, str(rates[2]), size=15, ha='center', va='center', color='green')
        ax1.text(2500, 4, str(rates[3]), size=15, ha='center', va='center', color='green')
        ax1.text(3500, 4, str(rates[4])+ r' $\frac{\mathsf{Spikes}}{\mathsf{s}}$', size=15, ha='center', va='center', color='green')
    plt.ylim([0,lims[1]+5])
    plt.xlim([0, 4000])
    plt.title('Histogram for ' + str(pic))
    ax1.set_xticklabels([-500, 'Start\nStimulus', 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000])
    plt.xlabel('Time (ms)')
    plt.ylabel('Counts (Spikes)')


    print lims
    arr_hand = getPic(pic)
    imagebox = OffsetImage(arr_hand, zoom=.3)
    xy = [3200, lims[1]+5]               # coordinates to position this image

    ab = AnnotationBbox(imagebox, xy, xybox=(30., -30.), xycoords='data',boxcoords="offset points")
    ax1.add_artist(ab)

    ax2 = ax1.twinx() #Necessary for multiple y-axes

    #Use ax2.plot to draw the hypnogram.  Be sure your x values are in seconds
    ax2.plot(xs, density(xs) , 'g', drawstyle='steps')
    plt.ylim([0,0.001])
    plt.yticks([0.0001,0.0002, 0.0003, 0.0004, 0.0005, 0.0006, 0.0007, 0.0008, 0.0009])
    ax2.set_yticklabels([1,2,3,4, 5, 6, 7, 8, 9])
    plt.ylabel(r'Density ($\cdot \mathsf{10^{-4}}$)', color='green')
    plt.gcf().subplots_adjust(right=0.89)
    plt.gcf().subplots_adjust(bottom=0.2)
    plt.savefig(pic, dpi=150)
开发者ID:sagar87,项目名称:Exploring-Neural-Data-Final-Project,代码行数:60,代码来源:final.py

示例5: plot_event_histogram

def plot_event_histogram(events, plot_type):
    from matplotlib.dates import date2num, num2date
    from matplotlib import ticker

    plt.figure(figsize=(12, 4))

    values = []
    for event in events:
        if plot_type == "depth":
            values.append(event["depth_in_km"])
        elif plot_type == "time":
            values.append(date2num(event["origin_time"].datetime))

    plt.hist(values, bins=250)

    if plot_type == "time":
        plt.gca().xaxis.set_major_formatter(ticker.FuncFormatter(
            lambda numdate, _: num2date(numdate).strftime('%Y-%d-%m')))
        plt.gcf().autofmt_xdate()
        plt.xlabel("Origin time (UTC)")
        plt.title("Origin time distribution (%i events)" % len(events))
    elif plot_type == "depth":
        plt.xlabel("Event depth in km")
        plt.title("Hypocenter depth distribution (%i events)" % len(events))

    plt.tight_layout()
开发者ID:seancug,项目名称:LASIF,代码行数:26,代码来源:visualization.py

示例6: existe_croche_bas

def existe_croche_bas(img,ecart,i,j):
	somme = 0
	rep = 0
	ecart = int(round(ecart))
	e2 = int(round(ecart/2))
	for x in range(i-e2,i):
		for y in range(j-e2,j):
			if x < img.shape[0] and y < img.shape[1]:
				if img[x][y] == 0:
					somme = 1 + somme
	if somme*100 >= pc_cro*e2*e2:
		p = plt2.Rectangle((j-e2,i-e2),e2,e2,color='b')
		plt2.gcf().gca().add_artist(p)
		rep = 1
	else:
		somme = 0
		for x in range(i-e2,i):
			for y in range(j,j+e2):
				if x < img.shape[0] and y < img.shape[1]:
					if img[x][y] == 0:
						somme = 1 + somme
		if somme*100 >= pc_cro*e2*e2:
			p = plt2.Rectangle((j-e2,i-e2),e2,e2,color='b')
			plt2.gcf().gca().add_artist(p)
			rep = 1
	return rep
开发者ID:Elann,项目名称:stage,代码行数:26,代码来源:detect_barres.py

示例7: run_mag_test

def run_mag_test(fld, title="", show=False):
    vx, vy, vz = fld.component_views()  # pylint: disable=W0612
    vx, vy, vz = fld.component_fields()

    try:
        t0 = time()
        mag_ne = viscid.magnitude(fld, preferred="numexpr", only=False)
        t1 = time()
        logger.info("numexpr mag runtime: %g", t1 - t0)
    except viscid.verror.BackendNotFound:
        xfail("Numexpr is not installed")

    planes = ["z=0", "y=0"]
    nrows = 4
    ncols = len(planes)

    _, axes = plt.subplots(nrows, ncols, sharex=True, sharey=True, squeeze=False)

    for ind, p in enumerate(planes):
        vlt.plot(vx, p, ax=axes[0, ind], show=False)
        vlt.plot(vy, p, ax=axes[1, ind], show=False)
        vlt.plot(vz, p, ax=axes[2, ind], show=False)
        vlt.plot(mag_ne, p, ax=axes[3, ind], show=False)

    plt.suptitle(title)
    vlt.auto_adjust_subplots(subplot_params=dict(top=0.9, right=0.9))
    plt.gcf().set_size_inches(6, 7)

    plt.savefig(next_plot_fname(__file__))
    if show:
        vlt.mplshow()
开发者ID:KristoforMaynard,项目名称:Viscid,代码行数:31,代码来源:test_calc.py

示例8: beautify

def beautify():
    """Format the figure of the run length distribution.

    Used in conjunction with plot method (obsolete/outdated, see functions ``beautifyFVD`` and ``beautifyRLD``).

    """
    # raise NotImplementedError('this implementation is obsolete')
    plt.subplot(121)
    axisHandle = plt.gca()
    axisHandle.set_xscale('log')
    axisHandle.set_xlabel('log10 of FEvals / DIM')
    axisHandle.set_ylabel('proportion of trials')
    # Grid options
    logxticks()
    beautifyECDF()

    plt.subplot(122)
    axisHandle = plt.gca()
    axisHandle.set_xscale('log')
    xmin, fmax = plt.xlim()
    plt.xlim(1., fmax)
    axisHandle.set_xlabel('log10 of Df / Dftarget')
    beautifyECDF()
    logxticks()
    axisHandle.set_yticklabels(())
    plt.gcf().set_size_inches(16.35, 6.175)
开发者ID:NDManh,项目名称:numbbo,代码行数:26,代码来源:pprldistr.py

示例9: main

def main():
    plt.figure(figsize=[8, 8])
    ax = plt.axes(projection=ccrs.SouthPolarStereo())

    ax.coastlines()
    ax.gridlines()

    im = ax.stock_img()

    def on_draw(event=None):
        """
        Hooks into matplotlib's event mechanism to define the clip path of the
        background image.

        """
        # Clip the image to the current background boundary.
        im.set_clip_path(ax.background_patch.get_path(), transform=ax.background_patch.get_transform())

    # Register the on_draw method and call it once now.
    plt.gcf().canvas.mpl_connect("draw_event", on_draw)
    on_draw()

    # Generate a matplotlib path representing the character "C".
    fp = FontProperties(family="Bitstream Vera Sans", weight="bold")
    logo_path = matplotlib.textpath.TextPath((-4.5e7, -3.7e7), "C", size=1, prop=fp)

    # Scale the letter up to an appropriate X and Y scale.
    logo_path._vertices *= np.array([103250000, 103250000])

    # Add the path as a patch, drawing black outlines around the text.
    patch = matplotlib.patches.PathPatch(
        logo_path, facecolor="white", edgecolor="black", linewidth=10, transform=ccrs.SouthPolarStereo()
    )
    ax.add_patch(patch)
    plt.show()
开发者ID:QuLogic,项目名称:cartopy,代码行数:35,代码来源:favicon.py

示例10: test_plot_tfr_topomap

def test_plot_tfr_topomap():
    """Test plotting of TFR data
    """
    import matplotlib as mpl
    import matplotlib.pyplot as plt

    raw = _get_raw()
    times = np.linspace(-0.1, 0.1, 200)
    n_freqs = 3
    nave = 1
    rng = np.random.RandomState(42)
    data = rng.randn(len(raw.ch_names), n_freqs, len(times))
    tfr = AverageTFR(raw.info, data, times, np.arange(n_freqs), nave)
    tfr.plot_topomap(ch_type="mag", tmin=0.05, tmax=0.150, fmin=0, fmax=10, res=16)

    eclick = mpl.backend_bases.MouseEvent("button_press_event", plt.gcf().canvas, 0, 0, 1)
    eclick.xdata = 0.1
    eclick.ydata = 0.1
    eclick.inaxes = plt.gca()
    erelease = mpl.backend_bases.MouseEvent("button_release_event", plt.gcf().canvas, 0.9, 0.9, 1)
    erelease.xdata = 0.3
    erelease.ydata = 0.2
    pos = [[0.11, 0.11], [0.25, 0.5], [0.0, 0.2], [0.2, 0.39]]
    _onselect(eclick, erelease, tfr, pos, "mag", 1, 3, 1, 3, "RdBu_r", list())
    tfr._onselect(eclick, erelease, None, "mean", None)
    plt.close("all")
开发者ID:Teekuningas,项目名称:mne-python,代码行数:26,代码来源:test_topomap.py

示例11: plot

    def plot(self):
        self.artists = []
        axis = plt.subplot(111)

        for i, plot_inst in enumerate(sorted(self.plot_instances, key=lambda pi: pi.sort_order)):
            self.artists.extend(plot_inst.plot(axis, i))
            
        self.print_shortcuts()

        axis.set_xlabel('time')
        axis.set_xticklabels(axis.get_xticks(), rotation=90, fontsize=10)
        axis.xaxis.set_major_formatter(DateFormatter('%b %d\n%H:%M:%S'))

        for label in axis.get_xticklabels():  # make the xtick labels pickable
            label.set_picker(True)

        # log y axis
        if self.args['log']:
            axis.set_yscale('log')
            axis.set_ylabel('query duration in ms (log scale)')
        else:
            axis.set_ylabel('query duration in ms')

        handles, labels = axis.get_legend_handles_labels()
        if len(labels) > 0:
            self.legend = axis.legend(loc='upper left', frameon=False, numpoints=1, fontsize=9)

        plt.gcf().canvas.mpl_connect('pick_event', self.onpick)
        plt.gcf().canvas.mpl_connect('key_press_event', self.onpress)

        plt.show()
开发者ID:aheckmann,项目名称:mtools,代码行数:31,代码来源:mplotqueries.py

示例12: update

def update(frame_number):
    plt.cla()
    if map_msg is not None:
        for lane in map_msg.hdmap.lane:
            draw_lane_boundary(lane, ax, 'b', map_msg.lane_marker)
            draw_lane_central(lane, ax, 'r')

        for key in map_msg.navigation_path:
            x = []
            y = []
            for point in map_msg.navigation_path[key].path.path_point:
                x.append(point.y)
                y.append(point.x)
            ax.plot(x, y, ls='-', c='g', alpha=0.3)

    if planning_msg is not None:
        x = []
        y = []
        for tp in planning_msg.trajectory_point:
            x.append(tp.path_point.y)
            y.append(tp.path_point.x)
        ax.plot(x, y, ls=':', c='r', linewidth=5.0)

    ax.axvline(x=0.0, alpha=0.3)
    ax.axhline(y=0.0, alpha=0.3)
    ax.set_xlim([10, -10])
    ax.set_ylim([-10, 200])
    y = 10
    while y < 200:
        ax.plot([10, -10], [y, y], ls='-', c='g', alpha=0.3)
        y = y + 10
    plt.yticks(np.arange(10, 200, 10))
    adc = plt.Circle((0, 0), 0.3, color='r')
    plt.gcf().gca().add_artist(adc)
    ax.relim()
开发者ID:GeoffGao,项目名称:apollo,代码行数:35,代码来源:relative_map_viewer.py

示例13: plot_scatter

def plot_scatter(points, rects, level_id, fig_area=FIG_AREA, grid_area=GRID_AREA, with_axis=False, with_img=True, img_alpha=1.0):
    rect = rects[level_id]
    top_lat, top_lng, bot_lat, bot_lng = get_rect_bounds(rect)

    plevel = get_points_level(points, rects, level_id)
    ax = plevel.plot('lng', 'lat', 'scatter')
    plt.xlim(left=top_lng, right=bot_lng)
    plt.ylim(top=top_lat, bottom=bot_lat)

    if with_img:
        img = plt.imread('/data/images/level%s.png' % level_id)
        plt.imshow(img, zorder=0, alpha=img_alpha, extent=[top_lng, bot_lng, bot_lat, top_lat])

    width, height = get_rect_width_height(rect)
    fig_width, fig_height = get_fig_width_height(width, height, fig_area)
    plt.gcf().set_size_inches(fig_width, fig_height)

    if grid_area:
        grid_horiz, grid_vertic = get_grids(rects, level_id, grid_area, fig_area)
        for lat in grid_horiz:
            plt.axhline(lat, color=COLOR_GRID, lw=GRID_LW)
        for lng in grid_vertic:
            plt.axvline(lng, color=COLOR_GRID, lw=GRID_LW)

    if not with_axis:
        ax.set_axis_off()
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)

    return ax
开发者ID:tentangdata,项目名称:pinisi,代码行数:30,代码来源:functions.py

示例14: main

def main():
    start = datetime(2006, 1, 1, 0, 0, 0, 0, pytz.utc)
    end = datetime(2014, 8, 25, 0, 0, 0, 0, pytz.utc)

    data = zp.utils.factory.load_bars_from_yahoo(stocks=[stock],
                                                 start=start,
                                                 end=end,
                                                 adjusted=True)
    algo = MyAlgo()
    perf = algo.run(data)

    fig = plt.figure()
    ax1 = fig.add_subplot(211,  ylabel='Price in $')
    data[stock]['close'].plot(ax=ax1, color='r', lw=2.)
    perf[['short_ma', 'long_ma']].plot(ax=ax1, lw=2.)

    ax1.plot(perf.ix[perf.buy].index, perf.short_ma[perf.buy],
             '^', markersize=10, color='m')
    ax1.plot(perf.ix[perf.sell].index, perf.short_ma[perf.sell],
             'v', markersize=10, color='k')

    ax2 = fig.add_subplot(212, ylabel='Portfolio value in $')
    perf.portfolio_value.plot(ax=ax2, lw=2.)

    ax2.plot(perf.ix[perf.buy].index, perf.portfolio_value[perf.buy],
             '^', markersize=10, color='m')
    ax2.plot(perf.ix[perf.sell].index, perf.portfolio_value[perf.sell],
             'v', markersize=10, color='k')

    plt.legend(loc=0)
    plt.gcf().set_size_inches(14, 10)
    plt.show()
开发者ID:zhoubug,项目名称:stock,代码行数:32,代码来源:algo.py

示例15: plot

def plot( name, data ) :
    
    dates = data["date"]
    times = data["time"]

    ddiff = max(dates)-min(dates)
    
    plt.close()
    plt.figure()    
    
    plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%b-%d %X'))
    
    # set x-axis scale
    if ddiff.days > 60 :
        plt.gca().xaxis.set_major_locator(mdates.MonthLocator())
    elif ddiff.days > 2 :
        plt.gca().xaxis.set_major_locator(mdates.DayLocator())
    else :
        plt.gca().xaxis.set_major_locator(mdates.HourLocator())

    plt.plot( dates, times, 'bo-' )
    plt.gcf().autofmt_xdate()    

    plt.title( name )
    plt.xlabel( "Date" )
    plt.ylabel( "Time (s)" )
    plt.grid(True)
    plt.setp(plt.gca().get_xmajorticklabels(), size=6,rotation=30) 
#    plt.show()
    plt.savefig( name )
开发者ID:michaelballantyne,项目名称:spatialops-threadfix,代码行数:30,代码来源:TimeLogger.py


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