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


Python pyplot.Figure方法代码示例

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


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

示例1: FigureToSummary

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import Figure [as 别名]
def FigureToSummary(name, fig):
  """Create tf.Summary proto from matplotlib.figure.Figure.

  Args:
    name: Summary name.
    fig: A matplotlib figure object.

  Returns:
    A `tf.Summary` proto containing the figure rendered to an image.
  """
  canvas = backend_agg.FigureCanvasAgg(fig)
  fig.canvas.draw()
  ncols, nrows = fig.canvas.get_width_height()
  png_file = six.BytesIO()
  canvas.print_figure(png_file)
  png_str = png_file.getvalue()
  return tf.Summary(value=[
      tf.Summary.Value(
          tag='%s/image' % name,
          image=tf.Summary.Image(
              height=nrows,
              width=ncols,
              colorspace=3,
              encoded_image_string=png_str))
  ]) 
开发者ID:tensorflow,项目名称:lingvo,代码行数:27,代码来源:plot.py

示例2: Curve

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import Figure [as 别名]
def Curve(name, figsize, xs, ys, setter=None, **kwargs):
  """Plot curve(s) to a `tf.Summary` proto.

  Args:
    name: Image summary name.
    figsize: A 2D tuple containing the overall figure (width, height) dimensions
      in inches.
    xs: x values for matplotlib.pyplot.plot.
    ys: y values for matplotlib.pyplot.plot.
    setter: A callable taking (fig, axes). Useful to fine-control layout of the
      figure, xlabel, xticks, etc.
    **kwargs: Extra args for matplotlib.pyplot.plot.

  Returns:
    A `tf.Summary` proto contains the line plot.
  """
  fig = plt.Figure(figsize=figsize, dpi=100, facecolor='white')
  axes = fig.add_subplot(1, 1, 1)
  axes.plot(xs, ys, '.-', **kwargs)
  if setter:
    setter(fig, axes)
  return FigureToSummary(name, fig) 
开发者ID:tensorflow,项目名称:lingvo,代码行数:24,代码来源:plot.py

示例3: fig2rgb_array

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import Figure [as 别名]
def fig2rgb_array(fig: plt.Figure, expand_batch_dimension: bool = True
                  ) -> np.ndarray:
    """
    Convert matplotlib figure to numpy RGB array

    Parameters
    ----------
    fig
        figure to convert
    expand_batch_dimension
        if the single batch dimension should be added

    Returns
    -------
    figure_as_array
        figure as numpy array

    """
    fig.canvas.draw()
    buf = fig.canvas.tostring_rgb()
    ncols, nrows = fig.canvas.get_width_height()
    shape = ((nrows, ncols, 3) if not expand_batch_dimension
             else (1, nrows, ncols, 3))
    return np.fromstring(buf, dtype=np.uint8).reshape(shape) 
开发者ID:audi,项目名称:nucleus7,代码行数:26,代码来源:np_utils.py

示例4: plot

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import Figure [as 别名]
def plot(self, **kwargs):
        """Plot current quadtree

        :param axes: Axes instance to plot in, defaults to None
        :type axes: [:py:class:`matplotlib.Axes`], optional
        :param figure: Figure instance to plot in, defaults to None
        :type figure: [:py:class:`matplotlib.Figure`], optional
        :param **kwargs: kwargs are passed into `plt.imshow`
        :type **kwargs: dict
        """
        self._initImagePlot(**kwargs)
        self.data = self._quadtree.leaf_matrix_means
        self.title = 'Quadtree Means'

        self._addInfoText()

        if self._show_plt:
            plt.show() 
开发者ID:pyrocko,项目名称:kite,代码行数:20,代码来源:plot2d.py

示例5: __init__

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import Figure [as 别名]
def __init__(self, _: Simulation, print_props: Tuple[prp.Property]):
        """
        Constructor.

        Sets here is ft_per_deg_lon, which depends dynamically on aircraft's
        longitude (because of the conversion between geographic and Euclidean
        coordinate systems). We retrieve longitude from the simulation and
        assume it is constant thereafter.

        :param _: (unused) Simulation that will be plotted
        :param print_props: Propertys which will have their values printed to Figure.
            Must be retrievable from the plotted Simulation.
        """
        self.print_props = print_props
        self.figure: plt.Figure = None
        self.axes: AxesTuple = None
        self.value_texts: Tuple[plt.Text] = None 
开发者ID:Gor-Ren,项目名称:gym-jsbsim,代码行数:19,代码来源:visualiser.py

示例6: _plot_and_save_attention

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import Figure [as 别名]
def _plot_and_save_attention(att_w, filename):
    """Plot and save an attention."""
    # dynamically import matplotlib due to not found error
    from matplotlib.ticker import MaxNLocator
    import os

    d = os.path.dirname(filename)
    if not os.path.exists(d):
        os.makedirs(d)
    w, h = plt.figaspect(1.0 / len(att_w))
    fig = plt.Figure(figsize=(w * 2, h * 2))
    axes = fig.subplots(1, len(att_w))
    if len(att_w) == 1:
        axes = [axes]
    for ax, aw in zip(axes, att_w):
        # plt.subplot(1, len(att_w), h)
        ax.imshow(aw, aspect="auto")
        ax.set_xlabel("Input")
        ax.set_ylabel("Output")
        ax.xaxis.set_major_locator(MaxNLocator(integer=True))
        ax.yaxis.set_major_locator(MaxNLocator(integer=True))
    fig.tight_layout()
    return fig 
开发者ID:espnet,项目名称:espnet,代码行数:25,代码来源:plot.py

示例7: __init__

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import Figure [as 别名]
def __init__(self, main_window, locs):
        super().__init__()
        self.main_window = main_window
        self.locs = locs
        self.figure = plt.Figure()
        self.canvas = FigureCanvasQTAgg(self.figure)
        self.plot()
        vbox = QtWidgets.QVBoxLayout()
        self.setLayout(vbox)
        vbox.addWidget(self.canvas)
        vbox.addWidget((NavigationToolbar2QT(self.canvas, self)))
        self.setWindowTitle("Picasso: Filter")
        this_directory = os.path.dirname(os.path.realpath(__file__))
        icon_path = os.path.join(this_directory, "icons", "filter.ico")
        icon = QtGui.QIcon(icon_path)
        self.setWindowIcon(icon) 
开发者ID:jungmannlab,项目名称:picasso,代码行数:18,代码来源:filter.py

示例8: __init__

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import Figure [as 别名]
def __init__(self, window_title):
        super().__init__()
        self.setWindowTitle(window_title)
        this_directory = os.path.dirname(os.path.realpath(__file__))
        icon_path = os.path.join(this_directory, "icons", "nanotron.ico")
        icon = QtGui.QIcon(icon_path)
        self.setWindowIcon(icon)
        self.resize(1000, 500)
        self.figure = plt.Figure()
        self.canvas = FigureCanvas(self.figure)
        vbox = QtWidgets.QVBoxLayout()
        self.setLayout(vbox)
        vbox.addWidget(self.canvas)

        self.toolbar = NavigationToolbar(self.canvas, self)
        vbox.addWidget(self.toolbar) 
开发者ID:jungmannlab,项目名称:picasso,代码行数:18,代码来源:nanotron.py

示例9: history_plot

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import Figure [as 别名]
def history_plot(train_hist, val_hist, model_name='', out_directory=None):
    """
    Plot the training history of a model.

    :param train_hist: array-like: training loss history
    :param val_hist: array-like: validation loss history
    :param model_name: str: name of model
    :param out_directory: str: if not None, save the figure to this directory
    :return: plt.Figure
    """
    fig = plt.figure()
    fig.set_size_inches(6, 4)
    plt.plot(train_hist, label='train MAE', linewidth=2)
    plt.plot(val_hist, label='val MAE', linewidth=2)
    plt.grid(True, color='lightgray', zorder=-100)
    plt.xlabel('epoch')
    plt.ylabel('MAE')
    plt.legend(loc='best')
    plt.title('%s training history' % model_name)
    if out_directory is not None:
        plt.savefig('%s/%s_history.pdf' % (out_directory, remove_chars(model_name)), bbox_inches='tight')
    return fig 
开发者ID:jweyn,项目名称:DLWP,代码行数:24,代码来源:plot_functions.py

示例10: plot_curve_with_area

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import Figure [as 别名]
def plot_curve_with_area(x: Iterable[float],
                         y: Iterable[float],
                         xlabel: Text = 'x',
                         ylabel: Text = 'y') -> plt.Figure:
  """Plot the curve defined by inputs and the area under the curve.

  All entries of x and y are required to lie between 0 and 1.
  For example, x could be recall and y precision, or x is fpr and y is tpr.

  Args:
    x: Values on x-axis (1d)
    y: Values on y-axis (must be same length as x)
    xlabel: Label for x axis
    ylabel: Label for y axis

  Returns:
    The matplotlib figure handle
  """
  fig = plt.figure()
  plt.plot([0, 1], [0, 1], 'k', lw=1.0)
  plt.plot(x, y, lw=2, label=f'AUC: {metrics.auc(x, y):.3f}')
  plt.xlabel(xlabel)
  plt.ylabel(ylabel)
  plt.legend()
  return fig 
开发者ID:tensorflow,项目名称:privacy,代码行数:27,代码来源:plotting.py

示例11: plot_histograms

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import Figure [as 别名]
def plot_histograms(train: Iterable[float],
                    test: Iterable[float],
                    xlabel: Text = 'x',
                    thresh: float = None) -> plt.Figure:
  """Plot histograms of training versus test metrics."""
  xmin = min(np.min(train), np.min(test))
  xmax = max(np.max(train), np.max(test))
  bins = np.linspace(xmin, xmax, 100)
  fig = plt.figure()
  plt.hist(test, bins=bins, density=True, alpha=0.5, label='test', log='y')
  plt.hist(train, bins=bins, density=True, alpha=0.5, label='train', log='y')
  if thresh is not None:
    plt.axvline(thresh, c='r', label=f'threshold = {thresh:.3f}')
  plt.xlabel(xlabel)
  plt.ylabel('normalized counts (density)')
  plt.legend()
  return fig 
开发者ID:tensorflow,项目名称:privacy,代码行数:19,代码来源:plotting.py

示例12: test_bpt

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import Figure [as 别名]
def test_bpt(self, maps, useoi):
        if maps.bptsums is None:
            pytest.skip('no bpt data found in galaxy test data')

        bptflag = 'nooi' if useoi is False else 'global'

        masks, figure, axes = maps.get_bpt(show_plot=False, return_figure=True, use_oi=useoi)
        assert isinstance(figure, plt.Figure)

        for mech in self.mechanisms:
            assert mech in masks.keys()
            assert np.sum(masks[mech]['global']) == maps.bptsums[bptflag][mech]

        if useoi:
            assert len(axes) == 4
        else:
            assert len(axes) == 3

        for ax in axes:
            assert isinstance(ax, LocatableAxes) 
开发者ID:sdss,项目名称:marvin,代码行数:22,代码来源:test_bpt.py

示例13: figure_image_adjustment

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import Figure [as 别名]
def figure_image_adjustment(fig, img_size):
    """ adjust figure as nice image without axis

    :param fig: Figure
    :param tuple(int,int) img_size: image size
    :return Figure:

    >>> fig = figure_image_adjustment(plt.figure(), (150, 200))
    >>> isinstance(fig, matplotlib.figure.Figure)
    True
    """
    ax = fig.gca()
    ax.set(xlim=[0, img_size[1]], ylim=[img_size[0], 0])
    ax.axis('off')
    ax.axes.get_xaxis().set_ticklabels([])
    ax.axes.get_yaxis().set_ticklabels([])
    fig.tight_layout(pad=0)
    fig.subplots_adjust(left=0, right=1, top=1, bottom=0)
    return fig 
开发者ID:Borda,项目名称:pyImSegm,代码行数:21,代码来源:drawing.py

示例14: create_figure_by_image

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import Figure [as 别名]
def create_figure_by_image(img_size, subfig_size, nb_subfigs=1, extend=0.):
    """ crearting image according backround_image

    :param tuple(int,int) img_size: image size
    :param float subfig_size: maximal sub-figure size
    :param int nb_subfigs: number of sub-figure
    :param float extend: extension
    :return tuple(Figure,list):
    """
    norm_size = np.array(img_size) / float(np.max(img_size))
    # reverse dimensions and scale by fig size
    if norm_size[0] >= norm_size[1]:  # horizontal
        fig_size = norm_size[::-1] * subfig_size * np.array([nb_subfigs, 1])
        fig_size[0] += extend * fig_size[0]
        fig, axarr = plt.subplots(ncols=nb_subfigs, figsize=fig_size)
    else:  # vertical
        fig_size = norm_size[::-1] * subfig_size * np.array([1, nb_subfigs])
        fig_size[0] += extend * fig_size[0]
        fig, axarr = plt.subplots(nrows=nb_subfigs, figsize=fig_size)
    return fig, axarr 
开发者ID:Borda,项目名称:pyImSegm,代码行数:22,代码来源:drawing.py

示例15: viz_memalloc

# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import Figure [as 别名]
def viz_memalloc(
    cls,
    ugraph,
    split_on_large_graph=True,
    num_tensors_per_split=20,
    figsize=None,
    fontsize=12,
    lw=12,
    cmap=_cm.BrBG_r,
    rand_seed=1111
  ):
    seed(rand_seed)
    if TensorAllocationPlanner.KWARGS_NAMESCOPE not in ugraph.attributes:
      logger.info('No tensor allocation plan to visualize: %s', ugraph.name)
      return plt.Figure()
    alloc_plan = ugraph.attributes[TensorAllocationPlanner.KWARGS_NAMESCOPE]
    topo_tensors = sorted(
      [tensor_name for tensor_name in alloc_plan.plan],
      key=lambda tensor_name: alloc_plan.plan[tensor_name].time_slot_start
    )
    return cls._draw_figs(topo_tensors, alloc_plan, cmap, figsize, fontsize, lw, split_on_large_graph, num_tensors_per_split) 
开发者ID:uTensor,项目名称:utensor_cgen,代码行数:23,代码来源:graph_viz.py


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