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


Python pyplot.gcf方法代码示例

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


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

示例1: test_emg_plot

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import gcf [as 别名]
def test_emg_plot():

    sampling_rate = 1000

    emg = nk.emg_simulate(duration=10, sampling_rate=1000, burst_number=3)
    emg_summary, _ = nk.emg_process(emg, sampling_rate=sampling_rate)

    # Plot data over samples.
    nk.emg_plot(emg_summary)
    # This will identify the latest figure.
    fig = plt.gcf()
    assert len(fig.axes) == 2
    titles = ["Raw and Cleaned Signal", "Muscle Activation"]
    for (ax, title) in zip(fig.get_axes(), titles):
        assert ax.get_title() == title
    assert fig.get_axes()[1].get_xlabel() == "Samples"
    np.testing.assert_array_equal(fig.axes[0].get_xticks(), fig.axes[1].get_xticks())
    plt.close(fig)

    # Plot data over time.
    nk.emg_plot(emg_summary, sampling_rate=sampling_rate)
    # This will identify the latest figure.
    fig = plt.gcf()
    assert fig.get_axes()[1].get_xlabel() == "Time (seconds)" 
开发者ID:neuropsychology,项目名称:NeuroKit,代码行数:26,代码来源:tests_emg.py

示例2: test_eog_plot

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import gcf [as 别名]
def test_eog_plot():

    eog_signal = nk.data("eog_200hz")["vEOG"]
    signals, info = nk.eog_process(eog_signal, sampling_rate=200)

    # Plot
    nk.eog_plot(signals)
    fig = plt.gcf()
    assert len(fig.axes) == 2

    titles = ["Raw and Cleaned Signal", "Blink Rate"]
    legends = [["Raw", "Cleaned", "Blinks"], ["Rate", "Mean"]]
    ylabels = ["Amplitude (mV)", "Blinks per minute"]

    for (ax, title, legend, ylabel) in zip(fig.get_axes(), titles, legends, ylabels):
        assert ax.get_title() == title
        subplot = ax.get_legend_handles_labels()
        assert subplot[1] == legend
        assert ax.get_ylabel() == ylabel

    assert fig.get_axes()[1].get_xlabel() == "Samples"
    np.testing.assert_array_equal(fig.axes[0].get_xticks(), fig.axes[1].get_xticks())
    plt.close(fig) 
开发者ID:neuropsychology,项目名称:NeuroKit,代码行数:25,代码来源:tests_eog.py

示例3: test_eda_plot

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import gcf [as 别名]
def test_eda_plot():

    sampling_rate = 1000
    eda = nk.eda_simulate(duration=30, sampling_rate=sampling_rate, scr_number=6, noise=0, drift=0.01, random_state=42)
    eda_summary, _ = nk.eda_process(eda, sampling_rate=sampling_rate)

    # Plot data over samples.
    nk.eda_plot(eda_summary)
    # This will identify the latest figure.
    fig = plt.gcf()
    assert len(fig.axes) == 3
    titles = ["Raw and Cleaned Signal", "Skin Conductance Response (SCR)", "Skin Conductance Level (SCL)"]
    for (ax, title) in zip(fig.get_axes(), titles):
        assert ax.get_title() == title
    assert fig.get_axes()[2].get_xlabel() == "Samples"
    np.testing.assert_array_equal(fig.axes[0].get_xticks(), fig.axes[1].get_xticks(), fig.axes[2].get_xticks())
    plt.close(fig)

    # Plot data over seconds.
    nk.eda_plot(eda_summary, sampling_rate=sampling_rate)
    # This will identify the latest figure.
    fig = plt.gcf()
    assert fig.get_axes()[2].get_xlabel() == "Seconds" 
开发者ID:neuropsychology,项目名称:NeuroKit,代码行数:25,代码来源:tests_eda.py

示例4: plot

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import gcf [as 别名]
def plot(self, line_width=1, point_radius=math.sqrt(2.0), annotation_size=8, dpi=120, save=True, name=None):
        x = [self.nodes[i][0] for i in self.global_best_tour]
        x.append(x[0])
        y = [self.nodes[i][1] for i in self.global_best_tour]
        y.append(y[0])
        plt.plot(x, y, linewidth=line_width)
        plt.scatter(x, y, s=math.pi * (point_radius ** 2.0))
        plt.title(self.mode)
        for i in self.global_best_tour:
            plt.annotate(self.labels[i], self.nodes[i], size=annotation_size)
        if save:
            if name is None:
                name = '{0}.png'.format(self.mode)
            plt.savefig(name, dpi=dpi)
        plt.show()
        plt.gcf().clear() 
开发者ID:rochakgupta,项目名称:aco-tsp,代码行数:18,代码来源:aco_tsp.py

示例5: test_root_locus_zoom

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import gcf [as 别名]
def test_root_locus_zoom(self):
        """Check the zooming functionality of the Root locus plot"""
        system = TransferFunction([1000], [1, 25, 100, 0])
        root_locus(system)
        fig = plt.gcf()
        ax_rlocus = fig.axes[0]

        event = type('test', (object,), {'xdata': 14.7607954359, 'ydata': -35.6171379864, 'inaxes': ax_rlocus.axes})()
        ax_rlocus.set_xlim((-10.813628105112421, 14.760795435937652))
        ax_rlocus.set_ylim((-35.61713798641108, 33.879716621220311))
        plt.get_current_fig_manager().toolbar.mode = 'zoom rect'
        _RLClickDispatcher(event, system, fig, ax_rlocus, '-')

        zoom_x = ax_rlocus.lines[-2].get_data()[0][0:5]
        zoom_y = ax_rlocus.lines[-2].get_data()[1][0:5]
        zoom_y = [abs(y) for y in zoom_y]

        zoom_x_valid = [-5. ,- 4.61281263, - 4.16689986, - 4.04122642, - 3.90736502]
        zoom_y_valid = [0. ,0., 0., 0., 0.]

        assert_array_almost_equal(zoom_x,zoom_x_valid)
        assert_array_almost_equal(zoom_y,zoom_y_valid) 
开发者ID:python-control,项目名称:python-control,代码行数:24,代码来源:rlocus_test.py

示例6: test_custom_bode_default

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import gcf [as 别名]
def test_custom_bode_default(self):
        ct.config.defaults['bode.dB'] = True
        ct.config.defaults['bode.deg'] = True
        ct.config.defaults['bode.Hz'] = True

        # Generate a Bode plot
        plt.figure()
        omega = np.logspace(-3, 3, 100)
        ct.bode_plot(self.sys, omega, dB=True)
        mag_x, mag_y = (((plt.gcf().axes[0]).get_lines())[0]).get_data()
        np.testing.assert_almost_equal(mag_y[0], 20*log10(10), decimal=3)

        # Override defaults
        plt.figure()
        ct.bode_plot(self.sys, omega, Hz=True, deg=False, dB=True)
        mag_x, mag_y = (((plt.gcf().axes[0]).get_lines())[0]).get_data()
        phase_x, phase_y = (((plt.gcf().axes[1]).get_lines())[0]).get_data()
        np.testing.assert_almost_equal(mag_x[0], 0.001 / (2*pi), decimal=6)
        np.testing.assert_almost_equal(mag_y[0], 20*log10(10), decimal=3)
        np.testing.assert_almost_equal(phase_y[-1], -pi, decimal=2)

        ct.reset_defaults() 
开发者ID:python-control,项目名称:python-control,代码行数:24,代码来源:config_test.py

示例7: plot_filters

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import gcf [as 别名]
def plot_filters(filters):
    '''Create a plot of conv filters, visualized as pixel arrays.'''
    imgs = filters.get_value()

    N, channels, x, y = imgs.shape
    n = int(np.sqrt(N))
    assert n * n == N, 'filters must contain a square number of rows!'
    assert channels == 1 or channels == 3, 'can only plot grayscale or rgb filters!'

    img = np.zeros(((y+1) * n - 1, (x+1) * n - 1, channels), dtype=imgs[0].dtype)
    for i, pix in enumerate(imgs):
        r, c = divmod(i, n)
        img[r * (y+1):(r+1) * (y+1) - 1,
            c * (x+1):(c+1) * (x+1) - 1] = pix.transpose((1, 2, 0))

    img -= img.min()
    img /= img.max()

    ax = plt.gcf().add_subplot(111)
    ax.xaxis.set_visible(False)
    ax.yaxis.set_visible(False)
    ax.set_frame_on(False)
    ax.imshow(img.squeeze(), cmap=plt.cm.gray) 
开发者ID:feynmanliang,项目名称:bachbot,代码行数:25,代码来源:utils.py

示例8: create_image

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import gcf [as 别名]
def create_image(D, filename, filepath = '_static/'):
    # if any(D.size == 0):
    #     D = pg.text('?')
    qp(D)
    fig = plt.gcf()
    # ax = plt.gca()
    scale = 0.75
    fig.set_size_inches(10*scale, 4*scale, forward=True)
    # ax.autoscale()
    # plt.draw()
    # plt.show(block = False)
    filename +=  '.png'
    filepathfull = os.path.join(os.path.curdir, filepath, filename)
    print(filepathfull)
    fig.savefig(filepathfull, dpi=int(96/scale))


# example-rectangle 
开发者ID:amccaugh,项目名称:phidl,代码行数:20,代码来源:gen_geometry.py

示例9: frames_to_gif

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import gcf [as 别名]
def frames_to_gif(frames, prefix, save_dir, interval=50, fps=30):
    """
    Convert frames to gif file
    """
    assert len(frames) > 0
    plt.figure(figsize=(frames[0].shape[1] / 72.,
                        frames[0].shape[0] / 72.), dpi=72)
    patch = plt.imshow(frames[0])
    plt.axis('off')

    def animate(i):
        patch.set_data(frames[i])

    # TODO: interval should be 1000 / fps ?
    anim = animation.FuncAnimation(
        plt.gcf(), animate, frames=len(frames), interval=interval)
    output_path = "{}/{}.gif".format(save_dir, prefix)
    anim.save(output_path, writer='imagemagick', fps=fps) 
开发者ID:keiohta,项目名称:tf2rl,代码行数:20,代码来源:utils.py

示例10: example_1

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import gcf [as 别名]
def example_1():
    """Run example 1"""
    # script inputs
    mod_path = os.path.dirname(os.path.abspath(__file__))  # current module
    air_path = os.path.join(mod_path, '..',
                            'tests', 'test_utils', 'files', 'demo_selig.dat')

    # load coordinates from a a selig-style airfoil file
    air_df = read_selig(air_path)

    # plot the airfoil
    plot_airfoil(air_df)

    # save the png for the documentation
    fig = plt.gcf()
    save_name = os.path.basename(__file__).replace('.py', '.png')  # file name
    save_path = os.path.join(mod_path, save_name)
    fig.savefig(save_path) 
开发者ID:jennirinker,项目名称:code-for-the-world,代码行数:20,代码来源:example_1.py

示例11: state

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import gcf [as 别名]
def state(self):
        img = np.copy(self.world[self.sight_range:self.world.shape[0]-self.sight_range,self.sight_range:self.world.shape[0]-self.sight_range])
        img[img==0] = 256
        img[img==1] = 215
        img[img==2] = 123
        img[img==3] = 175
        img[img==9] = 1
        p = plt.imshow(img, interpolation='nearest', cmap='nipy_spectral')
        fig = plt.gcf()
        c1 = mpatches.Patch(color='red', label='cats')
        c2 = mpatches.Patch(color='green', label='mice')
        c3 = mpatches.Patch(color='yellow', label='cheese')
        plt.legend(handles=[c1,c2,c3],loc='center left',bbox_to_anchor=(1, 0.5))
        #plt.savefig("cat_mouse%i.png" % self.gif, bbox_inches='tight')
        #self.gif += 1
        plt.pause(0.1)
        
# Run algorithm 
开发者ID:iamshang1,项目名称:Projects,代码行数:20,代码来源:cat_mouse.py

示例12: run_story_evaluation

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import gcf [as 别名]
def run_story_evaluation(story_file, policy_model_path, nlu_model_path,
                         out_file, max_stories):
    """Run the evaluation of the stories, plots the results."""
    from sklearn.metrics import confusion_matrix
    from sklearn.utils.multiclass import unique_labels

    test_y, preds = collect_story_predictions(story_file, policy_model_path,
                                              nlu_model_path, max_stories)

    log_evaluation_table(test_y, preds)
    cnf_matrix = confusion_matrix(test_y, preds)
    plot_confusion_matrix(cnf_matrix, classes=unique_labels(test_y, preds),
                          title='Action Confusion matrix')

    fig = plt.gcf()
    fig.set_size_inches(int(20), int(20))
    fig.savefig(out_file, bbox_inches='tight') 
开发者ID:Rowl1ng,项目名称:rasa_wechat,代码行数:19,代码来源:evaluate.py

示例13: plot

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import gcf [as 别名]
def plot(self, posys=None, axes=None):
        "Plots a sweep for each posy"
        if len(self["sweepvariables"]) != 1:
            print("SolutionArray.plot only supports 1-dimensional sweeps")
        if not hasattr(posys, "__len__"):
            posys = [posys]
        import matplotlib.pyplot as plt
        from .interactive.plot_sweep import assign_axes
        from . import GPBLU
        (swept, x), = self["sweepvariables"].items()
        posys, axes = assign_axes(swept, posys, axes)
        for posy, ax in zip(posys, axes):
            y = self(posy) if posy not in [None, "cost"] else self["cost"]
            ax.plot(x, y, color=GPBLU)
        if len(axes) == 1:
            axes, = axes
        return plt.gcf(), axes


# pylint: disable=too-many-branches,too-many-locals,too-many-statements 
开发者ID:convexengineering,项目名称:gpkit,代码行数:22,代码来源:solution_array.py

示例14: plot

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import gcf [as 别名]
def plot(self, posys=None, axes=None):
        "Plots the sweep for each posy"
        import matplotlib.pyplot as plt
        from ..interactive.plot_sweep import assign_axes
        from .. import GPBLU
        if not hasattr(posys, "__len__"):
            posys = [posys]
        for i, posy in enumerate(posys):
            if posy in [None, "cost"]:
                posys[i] = self.bst.costposy
        posys, axes = assign_axes(self.bst.sweptvar, posys, axes)
        for posy, ax in zip(posys, axes):
            if self._is_cost(posy):  # with small tol should look like a line
                ax.fill_between(self.sampled_at,
                                self.cost_lb(), self.cost_ub(),
                                facecolor=GPBLU, edgecolor=GPBLU,
                                linewidth=0.75)
            else:
                ax.plot(self.sampled_at, self(posy), color=GPBLU)
        if len(axes) == 1:
            axes, = axes
        return plt.gcf(), axes 
开发者ID:convexengineering,项目名称:gpkit,代码行数:24,代码来源:autosweep.py

示例15: load_and_plot_constraints_benchmark

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import gcf [as 别名]
def load_and_plot_constraints_benchmark():
    benchmark = np.loadtxt(fname='benchmark_constraints_time.dat')
    tried     = np.loadtxt(fname='benchmark_constraints_tried.dat')
    accepted  = np.loadtxt(fname='benchmark_constraints_accepted.dat')
    # plot
    keys = open('benchmark_constraints_time.dat').readlines()[0].split("#")[1].split()
    minY = 0
    maxY = 0
    for idx in range(1,len(keys)):
        style = '-'
        if keys[idx] == 'all':
            style = '.-'
        # mean accepted
        meanAccepted = int( sum(benchmark[:,0]*accepted[:,idx])/sum(benchmark[:,0]) )
        plt.plot(benchmark[:,0], benchmark[:,idx], style, label=keys[idx]+" (%i)"%meanAccepted)
        minY = min(minY, min(benchmark[:,idx]) )
        maxY = max(minY, max(benchmark[:,idx]) )
    # annotate tried(accepted)
    for i, txt in enumerate( accepted[:,-1] ):
        T = 100*float(tried[i,-1])/float(tried[1,1])
        A = 100*float(accepted[i,-1])/float(tried[1,1])
        plt.gca().annotate( "%.2f%% (%.2f%%)"%(T,A),  #"%i (%i)"%( int(tried[i,-1]),int(txt) ),
                            xy = (benchmark[i,0],benchmark[i,-1]),
                            rotation=90,
                            horizontalalignment='center',
                            verticalalignment='bottom')
    # show plot
    plt.legend(frameon=False, loc='upper left')
    plt.xlabel("Number of atoms per group")
    plt.ylabel("Time per step (s)")
    plt.gcf().patch.set_facecolor('white')
    # set fig size
    #figSize = plt.gcf().get_size_inches()
    #figSize[1] = figSize[1]+figSize[1]/2.
    #plt.gcf().set_size_inches(figSize, forward=True)
    plt.ylim((None, maxY+0.3*(maxY-minY)))
    # save
    plt.savefig("benchmark_constraint.png")
    # plot
    plt.show() 
开发者ID:bachiraoun,项目名称:fullrmc,代码行数:42,代码来源:run.py


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