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


Python pyplot.close方法代码示例

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


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

示例1: test_emg_plot

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import close [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: __init__

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import close [as 别名]
def __init__(self, title, varieties, data_points, attrs,
                 anim=False, data_func=None, is_headless=False):
        global anim_func

        plt.close()
        self.legend = ["Type"]
        self.title = title
        # self.anim = anim
        # self.data_func = data_func
        for i in varieties:
            data_points = len(varieties[i]["data"])
            break
        self.headless = is_headless
        self.draw_graph(data_points, varieties, attrs)

        # if anim and not self.headless:
        #     anim_func = animation.FuncAnimation(self.fig,
        #                                         self.update_plot,
        #                                         frames=1000,
        #                                         interval=500,
        #                                         blit=False) 
开发者ID:gcallah,项目名称:indras_net,代码行数:23,代码来源:display_methods.py

示例3: plot_alignment

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import close [as 别名]
def plot_alignment(alignment, gs, dir=hp.logdir):
    """Plots the alignment.

    Args:
      alignment: A numpy array with shape of (encoder_steps, decoder_steps)
      gs: (int) global step.
      dir: Output path.
    """
    if not os.path.exists(dir): os.mkdir(dir)

    fig, ax = plt.subplots()
    im = ax.imshow(alignment)

    fig.colorbar(im)
    plt.title('{} Steps'.format(gs))
    plt.savefig('{}/alignment_{}.png'.format(dir, gs), format='png')
    plt.close(fig) 
开发者ID:Kyubyong,项目名称:dc_tts,代码行数:19,代码来源:utils.py

示例4: plot

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import close [as 别名]
def plot(PDF, figName, imgpath, show=False, save=True):
    # plot
    output = PDF.get_constraint_value()
    plt.plot(PDF.experimentalDistances,PDF.experimentalPDF, 'ro', label="experimental", markersize=7.5, markevery=1 )
    plt.plot(PDF.shellsCenter, output["pdf"], 'k', linewidth=3.0,  markevery=25, label="total" )

    styleIndex = 0
    for key in output:
        val = output[key]
        if key in ("pdf_total", "pdf"):
            continue
        elif "inter" in key:
            plt.plot(PDF.shellsCenter, val, STYLE[styleIndex], markevery=5, label=key.split('rdf_inter_')[1] )
            styleIndex+=1
    plt.legend(frameon=False, ncol=1)
    # set labels
    plt.title("$\\chi^{2}=%.6f$"%PDF.squaredDeviations, size=20)
    plt.xlabel("$r (\AA)$", size=20)
    plt.ylabel("$g(r)$", size=20)
    # show plot
    if save: plt.savefig(figName)
    if show: plt.show()
    plt.close() 
开发者ID:bachiraoun,项目名称:fullrmc,代码行数:25,代码来源:plotFigures.py

示例5: save_d_at_t

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import close [as 别名]
def save_d_at_t(outputs, global_step, output_dir, metric_summary, N):
  """Save distance to goal at all time steps.
  
  Args:
    outputs        : [gt_dist_to_goal].
    global_step : number of iterations.
    output_dir     : output directory.
    metric_summary : to append scalars to summary.
    N              : number of outputs to process.

  """
  d_at_t = np.concatenate(map(lambda x: x[0][:,:,0]*1, outputs), axis=0)
  fig, axes = utils.subplot(plt, (1,1), (5,5))
  axes.plot(np.arange(d_at_t.shape[1]), np.mean(d_at_t, axis=0), 'r.')
  axes.set_xlabel('time step')
  axes.set_ylabel('dist to next goal')
  axes.grid('on')
  file_name = os.path.join(output_dir, 'dist_at_t_{:d}.png'.format(global_step))
  with fu.fopen(file_name, 'w') as f:
    fig.savefig(f, bbox_inches='tight', transparent=True, pad_inches=0)
  file_name = os.path.join(output_dir, 'dist_at_t_{:d}.pkl'.format(global_step))
  utils.save_variables(file_name, [d_at_t], ['d_at_t'], overwrite=True)
  plt.close(fig)
  return None 
开发者ID:ringringyi,项目名称:DOTA_models,代码行数:26,代码来源:nav_utils.py

示例6: plot_images

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import close [as 别名]
def plot_images(imgs, targets, paths=None, fname='images.jpg'):
    # Plots training images overlaid with targets
    imgs = imgs.cpu().numpy()
    targets = targets.cpu().numpy()
    # targets = targets[targets[:, 1] == 21]  # plot only one class

    fig = plt.figure(figsize=(10, 10))
    bs, _, h, w = imgs.shape  # batch size, _, height, width
    bs = min(bs, 16)  # limit plot to 16 images
    ns = np.ceil(bs ** 0.5)  # number of subplots

    for i in range(bs):
        boxes = xywh2xyxy(targets[targets[:, 0] == i, 2:6]).T
        boxes[[0, 2]] *= w
        boxes[[1, 3]] *= h
        plt.subplot(ns, ns, i + 1).imshow(imgs[i].transpose(1, 2, 0))
        plt.plot(boxes[[0, 2, 2, 0, 0]], boxes[[1, 1, 3, 3, 1]], '.-')
        plt.axis('off')
        if paths is not None:
            s = Path(paths[i]).name
            plt.title(s[:min(len(s), 40)], fontdict={'size': 8})  # limit to 40 characters
    fig.tight_layout()
    fig.savefig(fname, dpi=200)
    plt.close() 
开发者ID:zbyuan,项目名称:pruning_yolov3,代码行数:26,代码来源:utils.py

示例7: plot_some_results

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import close [as 别名]
def plot_some_results(pred_fn, test_generator, n_images=10):
    fig_ctr = 0
    for data, seg in test_generator:
        res = pred_fn(data)
        for d, s, r in zip(data, seg, res):
            plt.figure(figsize=(12, 6))
            plt.subplot(1, 3, 1)
            plt.imshow(d.transpose(1,2,0))
            plt.title("input patch")
            plt.subplot(1, 3, 2)
            plt.imshow(s[0])
            plt.title("ground truth")
            plt.subplot(1, 3, 3)
            plt.imshow(r)
            plt.title("segmentation")
            plt.savefig("road_segmentation_result_%03.0f.png"%fig_ctr)
            plt.close()
            fig_ctr += 1
            if fig_ctr > n_images:
                break 
开发者ID:Lasagne,项目名称:Recipes,代码行数:22,代码来源:massachusetts_road_segm.py

示例8: classify

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import close [as 别名]
def classify(self, features, show=False):
        recs, _ = features.shape
        result_shape = (features.shape[0], len(self.root))
        scores = np.zeros(result_shape)
        print scores.shape
        R = Record(np.arange(recs, dtype=int), features)

        for i, T in enumerate(self.root):
            for idxs, result in classify(T, R):
                for idx in idxs.indexes():
                    scores[idx, i] = float(result[0]) / sum(result.values())


        if show:
            plt.cla()
            plt.clf()
            plt.close()

            plt.imshow(scores, cmap=plt.cm.gray)
            plt.title('Scores matrix')
            plt.savefig(r"../scratch/tree_scores.png", bbox_inches='tight')
        
        return scores 
开发者ID:gdanezis,项目名称:trees,代码行数:25,代码来源:malware.py

示例9: notify

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import close [as 别名]
def notify(self, algorithm, **kwargs):
        if algorithm.n_gen == 1 or algorithm.n_gen % self.nth_gen == 0:
            try:

                ret = self.do(algorithm.problem, algorithm, **kwargs)

                if self.do_show:
                    plt.show()

                if self.video is not None:
                    self.video.record()

                if self.do_close:
                    plt.close()

                return ret

            except Exception as ex:
                if self.exception_if_not_applicable:
                    raise ex 
开发者ID:msu-coinlab,项目名称:pymoo,代码行数:22,代码来源:callback_video.py

示例10: _render_price

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import close [as 别名]
def _render_price(self, step_range, times, current_step):
        self.price_ax.clear()

        # Plot price using candlestick graph from mpl_finance
        self.price_ax.plot(times, self.df['close'].values[step_range], color="black")

        last_time = self.df.index.values[current_step]
        last_close = self.df['close'].values[current_step]
        last_high = self.df['high'].values[current_step]

        # Print the current price to the price axis
        self.price_ax.annotate('{0:.2f}'.format(last_close), (last_time, last_close),
                               xytext=(last_time, last_high),
                               bbox=dict(boxstyle='round',
                                         fc='w', ec='k', lw=1),
                               color="black",
                               fontsize="small")

        # Shift price axis up to give volume chart space
        ylim = self.price_ax.get_ylim()
        self.price_ax.set_ylim(ylim[0] - (ylim[1] - ylim[0]) * VOLUME_CHART_HEIGHT, ylim[1]) 
开发者ID:tensortrade-org,项目名称:tensortrade,代码行数:23,代码来源:matplotlib_trading_chart.py

示例11: _render_trades

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import close [as 别名]
def _render_trades(self, step_range, trades):
        trades = [trade for sublist in trades.values() for trade in sublist]

        for trade in trades:
            if trade.step in range(sys.maxsize)[step_range]:
                date = self.df.index.values[trade.step]
                close = self.df['close'].values[trade.step]
                color = 'green'

                if trade.side is TradeSide.SELL:
                    color = 'red'

                self.price_ax.annotate(' ', (date, close),
                                       xytext=(date, close),
                                       size="large",
                                       arrowprops=dict(arrowstyle='simple', facecolor=color)) 
开发者ID:tensortrade-org,项目名称:tensortrade,代码行数:18,代码来源:matplotlib_trading_chart.py

示例12: generate_png_chess_dp_vertex

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import close [as 别名]
def generate_png_chess_dp_vertex(self):
    """Produces pictures of the dominant product vertex a chessboard convention"""
    import matplotlib.pylab as plt
    plt.ioff()
    dab2v = self.get_dp_vertex_doubly_sparse()
    for i, ab in enumerate(dab2v): 
        fname = "chess-v-{:06d}.png".format(i)
        print('Matrix No.#{}, Size: {}, Type: {}'.format(i+1, ab.shape, type(ab)), fname)
        if type(ab) != 'numpy.ndarray': ab = ab.toarray()
        fig = plt.figure()
        ax = fig.add_subplot(1,1,1)
        ax.set_aspect('equal')
        plt.imshow(ab, interpolation='nearest', cmap=plt.cm.ocean)
        plt.colorbar()
        plt.savefig(fname)
        plt.close(fig) 
开发者ID:pyscf,项目名称:pyscf,代码行数:18,代码来源:prod_basis.py

示例13: plot_species

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import close [as 别名]
def plot_species(statistics, view=False, filename='speciation.svg'):
    """ Visualizes speciation throughout evolution. """
    if plt is None:
        warnings.warn("This display is not available due to a missing optional dependency (matplotlib)")
        return

    species_sizes = statistics.get_species_sizes()
    num_generations = len(species_sizes)
    curves = np.array(species_sizes).T

    fig, ax = plt.subplots()
    ax.stackplot(range(num_generations), *curves)

    plt.title("Speciation")
    plt.ylabel("Size per Species")
    plt.xlabel("Generations")

    plt.savefig(filename)

    if view:
        plt.show()

    plt.close() 
开发者ID:CodeReclaimers,项目名称:neat-python,代码行数:25,代码来源:visualize.py

示例14: test_eog_plot

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import close [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

示例15: test_eda_plot

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import close [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


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