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


Python gridspec.GridSpec方法代码示例

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


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

示例1: plot

# 需要导入模块: from matplotlib import gridspec [as 别名]
# 或者: from matplotlib.gridspec import GridSpec [as 别名]
def plot(samples, size, name):
    size = int(size)
    fig = plt.figure(figsize=(4, 4))
    gs = gridspec.GridSpec(4, 4)
    gs.update(wspace=0.05, hspace=0.05)

    for i, sample in enumerate(samples):
        ax = plt.subplot(gs[i])
        plt.axis('off')
        ax.set_xticklabels([])
        ax.set_yticklabels([])
        ax.set_aspect('equal')
        plt.imshow(sample.reshape(size, size), cmap='Greys_r')

    plt.savefig('out/{}.png'.format(name), bbox_inches='tight')
    plt.close(fig) 
开发者ID:wiseodd,项目名称:generative-models,代码行数:18,代码来源:rbm_binary_pcd.py

示例2: visualization_init

# 需要导入模块: from matplotlib import gridspec [as 别名]
# 或者: from matplotlib.gridspec import GridSpec [as 别名]
def visualization_init(self):
        fig = plt.figure(figsize=(12, 6), frameon=False, tight_layout=True)
        fig.canvas.set_window_title(self.servoing_pol.predictor.name)
        gs = gridspec.GridSpec(1, 2)
        plt.show(block=False)

        return_plotter = LossPlotter(fig, gs[0],
                                     format_dicts=[dict(linewidth=2)] * 2,
                                     labels=['mean returns / 10', 'mean discounted returns'],
                                     ylabel='returns')
        return_major_locator = MultipleLocator(1)
        return_major_formatter = FormatStrFormatter('%d')
        return_minor_locator = MultipleLocator(1)
        return_plotter._ax.xaxis.set_major_locator(return_major_locator)
        return_plotter._ax.xaxis.set_major_formatter(return_major_formatter)
        return_plotter._ax.xaxis.set_minor_locator(return_minor_locator)

        learning_plotter = LossPlotter(fig, gs[1], format_dicts=[dict(linewidth=2)] * 2, ylabel='mean evaluation values')
        return fig, return_plotter, learning_plotter 
开发者ID:alexlee-gk,项目名称:visual_dynamics,代码行数:21,代码来源:cem.py

示例3: make_grid_spec

# 需要导入模块: from matplotlib import gridspec [as 别名]
# 或者: from matplotlib.gridspec import GridSpec [as 别名]
def make_grid_spec(
    ax_or_figsize: Union[Tuple[int, int], _AxesSubplot],
    nrows: int,
    ncols: int,
    wspace: Optional[float] = None,
    hspace: Optional[float] = None,
    width_ratios: Optional[Sequence[float]] = None,
    height_ratios: Optional[Sequence[float]] = None,
) -> Tuple[Figure, gridspec.GridSpecBase]:
    kw = dict(
        wspace=wspace,
        hspace=hspace,
        width_ratios=width_ratios,
        height_ratios=height_ratios,
    )
    if isinstance(ax_or_figsize, tuple):
        fig = pl.figure(figsize=ax_or_figsize)
        return fig, gridspec.GridSpec(nrows, ncols, **kw)
    else:
        ax = ax_or_figsize
        ax.axis('off')
        ax.set_frame_on(False)
        ax.set_xticks([])
        ax.set_yticks([])
        return ax.figure, ax.get_subplotspec().subgridspec(nrows, ncols, **kw) 
开发者ID:theislab,项目名称:scanpy,代码行数:27,代码来源:_utils.py

示例4: _panel_grid

# 需要导入模块: from matplotlib import gridspec [as 别名]
# 或者: from matplotlib.gridspec import GridSpec [as 别名]
def _panel_grid(hspace, wspace, ncols, num_panels):
    from matplotlib import gridspec

    n_panels_x = min(ncols, num_panels)
    n_panels_y = np.ceil(num_panels / n_panels_x).astype(int)
    # each panel will have the size of rcParams['figure.figsize']
    fig = pl.figure(
        figsize=(
            n_panels_x * rcParams['figure.figsize'][0] * (1 + wspace),
            n_panels_y * rcParams['figure.figsize'][1],
        ),
    )
    left = 0.2 / n_panels_x
    bottom = 0.13 / n_panels_y
    gs = gridspec.GridSpec(
        nrows=n_panels_y,
        ncols=n_panels_x,
        left=left,
        right=1 - (n_panels_x - 1) * left - 0.01 / n_panels_x,
        bottom=bottom,
        top=1 - (n_panels_y - 1) * bottom - 0.1 / n_panels_y,
        hspace=hspace,
        wspace=wspace,
    )
    return fig, gs 
开发者ID:theislab,项目名称:scanpy,代码行数:27,代码来源:scatterplots.py

示例5: plot_raster_cmp

# 需要导入模块: from matplotlib import gridspec [as 别名]
# 或者: from matplotlib.gridspec import GridSpec [as 别名]
def plot_raster_cmp(spike_trains, population=None, time_window=None, node_ids=None, ts_units=None, show_plot=True,
                    save_as=None, with_labels=False):
    spike_trains_l = _get_spike_trains(spike_trains)
    time_window = time_window or _find_time_window(spike_trains_l, population)
    labels = _build_labels_lu(with_labels, spike_trains)

    gs = gridspec.GridSpec(1, 1)
    for i, spikes in enumerate(spike_trains_l):
        spikes_df = spikes.to_dataframe(populations=population, time_window=time_window, node_ids=node_ids)
        ax1 = plt.subplot(gs[0])
        ax1.scatter(spikes_df['timestamps'], spikes_df['node_ids'], lw=0, s=5, label=labels[i])
        ax1.legend(loc=1, prop={'size': 10})
        ax1.set_xlim([time_window[0], time_window[1]])

    if save_as is not None:
        plt.savefig(save_as)

    if show_plot:
        plt.show() 
开发者ID:AllenInstitute,项目名称:sonata,代码行数:21,代码来源:plotting.py

示例6: get_gridspec

# 需要导入模块: from matplotlib import gridspec [as 别名]
# 或者: from matplotlib.gridspec import GridSpec [as 别名]
def get_gridspec(self, figure, nmr_plots):
        rows = self.rows
        cols = self.cols

        if rows is None and cols is None:
            return AutoGridLayout(spacings=self.spacings).get_gridspec(figure, nmr_plots)

        if rows is None:
            rows = int(np.ceil(nmr_plots / cols))
        if cols is None:
            cols = int(np.ceil(nmr_plots / rows))

        if rows * cols < nmr_plots:
            cols = int(np.ceil(nmr_plots / rows))

        return GridLayoutSpecifier(GridSpec(rows, cols, **self.spacings), figure) 
开发者ID:robbert-harms,项目名称:MDT,代码行数:18,代码来源:layouts.py

示例7: show_images

# 需要导入模块: from matplotlib import gridspec [as 别名]
# 或者: from matplotlib.gridspec import GridSpec [as 别名]
def show_images(images, rgb=True):
    gs = gridspec.GridSpec(1, len(images))
    for i, image in enumerate(images):
        plt.subplot(gs[0, i])
        if rgb:
            plt.imshow(image)
        else:
            image = image.reshape(image.shape[0], image.shape[1])
            plt.imshow(image, cmap='gray')
        plt.axis('off')
    plt.show() 
开发者ID:wdxtub,项目名称:deep-learning-note,代码行数:13,代码来源:16_basic_kernels.py

示例8: _hrv_plot

# 需要导入模块: from matplotlib import gridspec [as 别名]
# 或者: from matplotlib.gridspec import GridSpec [as 别名]
def _hrv_plot(peaks, out, sampling_rate=1000):

    fig = plt.figure(constrained_layout=False)
    spec = gs.GridSpec(ncols=2, nrows=2, height_ratios=[1, 1], width_ratios=[1, 1])

    # Arrange grids
    ax_distrib = fig.add_subplot(spec[0, :-1])
    ax_distrib.set_xlabel("R-R intervals (ms)")
    ax_distrib.set_title("Distribution of R-R intervals")

    ax_psd = fig.add_subplot(spec[1, :-1])

    spec_within = gs.GridSpecFromSubplotSpec(4, 4, subplot_spec=spec[:, -1], wspace=0.025, hspace=0.05)
    ax_poincare = fig.add_subplot(spec_within[1:4, 0:3])
    ax_marg_x = fig.add_subplot(spec_within[0, 0:3])
    ax_marg_x.set_title("Poincaré Plot")
    ax_marg_y = fig.add_subplot(spec_within[1:4, 3])

    # Distribution of RR intervals
    peaks = _hrv_sanitize_input(peaks)
    rri = _hrv_get_rri(peaks, sampling_rate=sampling_rate, interpolate=False)
    ax_distrib = summary_plot(rri, ax=ax_distrib)

    # Poincare plot
    out.columns = [col.replace("HRV_", "") for col in out.columns]
    _hrv_nonlinear_show(rri, out, ax=ax_poincare, ax_marg_x=ax_marg_x, ax_marg_y=ax_marg_y)

    # PSD plot
    rri, sampling_rate = _hrv_get_rri(peaks, sampling_rate=sampling_rate, interpolate=True)
    frequency_bands = out[["ULF", "VLF", "LF", "HF", "VHF"]]
    _hrv_frequency_show(rri, frequency_bands, sampling_rate=sampling_rate, ax=ax_psd) 
开发者ID:neuropsychology,项目名称:NeuroKit,代码行数:33,代码来源:hrv.py

示例9: _generate_4_axes_via_gridspec

# 需要导入模块: from matplotlib import gridspec [as 别名]
# 或者: from matplotlib.gridspec import GridSpec [as 别名]
def _generate_4_axes_via_gridspec():
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    import matplotlib.gridspec  # noqa

    gs = mpl.gridspec.GridSpec(2, 2)
    ax_tl = plt.subplot(gs[0, 0])
    ax_ll = plt.subplot(gs[1, 0])
    ax_tr = plt.subplot(gs[0, 1])
    ax_lr = plt.subplot(gs[1, 1])

    return gs, [ax_tl, ax_ll, ax_tr, ax_lr] 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:14,代码来源:test_frame.py

示例10: imgPixInColorSpace

# 需要导入模块: from matplotlib import gridspec [as 别名]
# 或者: from matplotlib.gridspec import GridSpec [as 别名]
def imgPixInColorSpace(pixData):
    fig = plt.figure()
    gs = gridspec.GridSpec(1, 3)

    im = fig.add_subplot(gs[0,0])
    im.imshow(pixData)
    im.set_title("2D Image")

    ax = fig.add_subplot(gs[0,1:3], projection='3d')
    colors = np.reshape(pixData, (pixData.shape[0] * pixData.shape[1], pixData.shape[2]))
    colors = colors / 255.0
    ax.scatter(pixData[:,:,0], pixData[:,:,1], pixData[:,:,2], c=colors)
    ax.set_xlabel("Red", color='red')
    ax.set_ylabel("Green", color='green')
    ax.set_zlabel("Blue", color='blue')

    ax.set_title("Image in Color Space")

    ax.set_xlim(0, 255)
    ax.set_ylim(0, 255)
    ax.set_zlim(0, 255)

    ax.xaxis.set_ticks([])
    ax.yaxis.set_ticks([])
    ax.zaxis.set_ticks([])


    plt.show() 
开发者ID:rainyear,项目名称:ImageColorTheme,代码行数:30,代码来源:test.py

示例11: imgPalette

# 需要导入模块: from matplotlib import gridspec [as 别名]
# 或者: from matplotlib.gridspec import GridSpec [as 别名]
def imgPalette(imgs, themes, titles):
    N = len(imgs)

    fig = plt.figure()
    gs  = gridspec.GridSpec(len(imgs), len(themes)+1)
    print(N)
    for i in range(N):
        im = fig.add_subplot(gs[i, 0])
        im.imshow(imgs[i])
        im.set_title("Image %s" % str(i+1))
        im.xaxis.set_ticks([])
        im.yaxis.set_ticks([])

        t = 1
        for themeLst in themes:
            theme = themeLst[i]
            pale = np.zeros(imgs[i].shape, dtype=np.uint8)
            h, w, _ = pale.shape
            ph  = h / len(theme)
            for y in range(h):
                pale[y,:,:] = np.array(theme[int(y / ph)], dtype=np.uint8)
            pl = fig.add_subplot(gs[i, t])
            pl.imshow(pale)
            pl.set_title(titles[t-1])
            pl.xaxis.set_ticks([])
            pl.yaxis.set_ticks([])

            t += 1

    plt.show() 
开发者ID:rainyear,项目名称:ImageColorTheme,代码行数:32,代码来源:test.py

示例12: __init__

# 需要导入模块: from matplotlib import gridspec [as 别名]
# 或者: from matplotlib.gridspec import GridSpec [as 别名]
def __init__(self,
               name,
               figsize=(8, 10),
               max_outputs=3,
               subplot_grid_shape=None,
               gridspec_kwargs=None,
               plot_func=AddImage,
               shared_subplot_kwargs=None):
    """Creates a new MatplotlibFigureSummary object.

    Args:
      name: A string name for the generated summary.
      figsize: A 2D tuple containing the overall figure (width, height)
        dimensions in inches.
      max_outputs: The maximum number of images to generate.
      subplot_grid_shape: A 2D tuple containing the height and width dimensions
        of the subplot grid.  height * width must be >= the number of subplots.
        Defaults to (num_subplots, 1), i.e. a vertical stack of plots.
      gridspec_kwargs: A dict of extra keyword args to use when initializing the
        figure's gridspec, as supported by matplotlib.gridspec.GridSpec.
      plot_func: A function shared across all subplots used to populate a single
        subplot.  See the docstring for AddSubplot for details.
      shared_subplot_kwargs: A dict of extra keyword args to pass to the plot
        function for all subplots.  This is useful for specifying properties
        such as 'clim' which should be consistent across all subplots.
    """
    self._name = name
    self._figsize = figsize
    self._max_outputs = max_outputs
    self._subplot_grid_shape = subplot_grid_shape
    self._gridspec_kwargs = gridspec_kwargs if gridspec_kwargs else {}
    self._plot_func = plot_func
    self._shared_subplot_kwargs = (
        shared_subplot_kwargs if shared_subplot_kwargs else {})
    self._subplots = [] 
开发者ID:tensorflow,项目名称:lingvo,代码行数:37,代码来源:plot.py

示例13: Finalize

# 需要导入模块: from matplotlib import gridspec [as 别名]
# 或者: from matplotlib.gridspec import GridSpec [as 别名]
def Finalize(self):
    """Finishes creation of the overall figure, returning the image summary."""
    subplot_grid_shape = self._subplot_grid_shape
    if subplot_grid_shape is None:
      subplot_grid_shape = (len(self._subplots), 1)

    # AddMatplotlibFigureSummary (due to restrictions of py_func) only supports
    # flattened list of tensors so we must do some bookkeeping to maintain a
    # mapping from _SubplotMetadata object to flattened_tensors.
    subplot_slices = []
    flattened_tensors = []
    for subplot in self._subplots:
      start = len(flattened_tensors)
      subplot_slices.append((start, start + len(subplot.tensor_list)))
      flattened_tensors.extend(subplot.tensor_list)

    def PlotFunc(fig, *numpy_data_list):
      gs = gridspec.GridSpec(*subplot_grid_shape, **self._gridspec_kwargs)
      for n, subplot in enumerate(self._subplots):
        axes = fig.add_subplot(gs[n])
        start, end = subplot_slices[n]
        subplot_data = numpy_data_list[start:end]
        subplot.plot_func(fig, axes, *subplot_data)

    func = functools.partial(_RenderMatplotlibFigures, self._figsize,
                             self._max_outputs, PlotFunc)
    batch_sizes = [tf.shape(t)[0] for t in flattened_tensors]
    num_tensors = len(flattened_tensors)
    with tf.control_dependencies([
        tf.assert_equal(
            batch_sizes, [batch_sizes[0]] * num_tensors, summarize=num_tensors)
    ]):
      rendered = tf.py_func(
          func, flattened_tensors, tf.uint8, name='RenderMatplotlibFigures')
    return tf.summary.image(self._name, rendered, max_outputs=self._max_outputs) 
开发者ID:tensorflow,项目名称:lingvo,代码行数:37,代码来源:plot.py

示例14: plot2d

# 需要导入模块: from matplotlib import gridspec [as 别名]
# 或者: from matplotlib.gridspec import GridSpec [as 别名]
def plot2d(u, learned_u, t):
    fig, ax = plt.subplots(nrows=1, ncols=1)
    ax.axis('off')

    gs0 = gridspec.GridSpec(3, 1)
    gs0.update(top=0.95, bottom=0.15, left=0.1, right=0.95, hspace=0.5)
    
    ax = plt.subplot(gs0[0:1, 0:1])
    ax.plot(t,u[:,0],'r-')
    ax.plot(t,learned_u[:,0],'k--')
    ax.set_xlabel('$t$')
    ax.set_ylabel('$x$')
    
    ax = plt.subplot(gs0[1:2, 0:1])
    ax.plot(t,u[:,1],'r-')
    ax.plot(t,learned_u[:,1],'k--')
    ax.set_xlabel('$t$')
    ax.set_ylabel('$y$')
    
    ax = plt.subplot(gs0[2:3, 0:1])
    ax.plot(t,u[:,2],'r-',label='Exact Dynamics')
    ax.plot(t,learned_u[:,2],'k--',label='Learned Dynamics')
    ax.set_xlabel('$t$')
    ax.set_ylabel('$z$')
    ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.4), ncol=2, frameon=False)

    plt.show() 
开发者ID:Kashu7100,项目名称:Qualia2.0,代码行数:29,代码来源:lorenz.py

示例15: _justified

# 需要导入模块: from matplotlib import gridspec [as 别名]
# 或者: from matplotlib.gridspec import GridSpec [as 别名]
def _justified(self, nrows, grid_arrangement):
        ax_specs = []
        num_small_cols = np.lcm.reduce(grid_arrangement)
        gs = gridspec.GridSpec(
            nrows, num_small_cols, figure=plt.figure(constrained_layout=True)
        )
        for r, row_cols in enumerate(grid_arrangement):
            skip = num_small_cols // row_cols
            for col in range(row_cols):
                s = col * skip
                e = s + skip

                ax_specs.append(gs[r, s:e])
        return ax_specs 
开发者ID:matplotlib,项目名称:grid-strategy,代码行数:16,代码来源:_abc.py


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