我们从Python开源项目中,提取了以下41个代码示例,用于说明如何使用matplotlib.axes()。
def _maybe_right_yaxis(self, ax, axes_num): if not self.on_right(axes_num): # secondary axes may be passed via ax kw return self._get_ax_layer(ax) if hasattr(ax, 'right_ax'): # if it has right_ax proparty, ``ax`` must be left axes return ax.right_ax elif hasattr(ax, 'left_ax'): # if it has left_ax proparty, ``ax`` must be right axes return ax else: # otherwise, create twin axes orig_ax, new_ax = ax, ax.twinx() # TODO: use Matplotlib public API when available new_ax._get_lines = orig_ax._get_lines new_ax._get_patches_for_fill = orig_ax._get_patches_for_fill orig_ax.right_ax, new_ax.left_ax = new_ax, orig_ax if not self._has_plotted_object(orig_ax): # no data on left y orig_ax.get_yaxis().set_visible(False) return new_ax
def result(self): """ Return result axes """ if self.subplots: if self.layout is not None and not com.is_list_like(self.ax): return self.axes.reshape(*self.layout) else: return self.axes else: sec_true = isinstance(self.secondary_y, bool) and self.secondary_y all_sec = (com.is_list_like(self.secondary_y) and len(self.secondary_y) == self.nseries) if (sec_true or all_sec): # if all data is plotted on secondary, return right axes return self._get_ax_layer(self.axes[0], primary=False) else: return self.axes[0]
def _make_plot(self): x, y, data, C = self.x, self.y, self.data, self.C ax = self.axes[0] # pandas uses colormap, matplotlib uses cmap. cmap = self.colormap or 'BuGn' cmap = self.plt.cm.get_cmap(cmap) cb = self.kwds.pop('colorbar', True) if C is None: c_values = None else: c_values = data[C].values ax.hexbin(data[x].values, data[y].values, C=c_values, cmap=cmap, **self.kwds) if cb: img = ax.collections[0] self.fig.colorbar(img, ax=ax)
def bar(self, **kwds): """ Vertical bar plot .. versionadded:: 0.17.0 Parameters ---------- **kwds : optional Keyword arguments to pass on to :py:meth:`pandas.Series.plot`. Returns ------- axes : matplotlib.AxesSubplot or np.array of them """ return self(kind='bar', **kwds)
def barh(self, **kwds): """ Horizontal bar plot .. versionadded:: 0.17.0 Parameters ---------- **kwds : optional Keyword arguments to pass on to :py:meth:`pandas.Series.plot`. Returns ------- axes : matplotlib.AxesSubplot or np.array of them """ return self(kind='barh', **kwds)
def box(self, **kwds): """ Boxplot .. versionadded:: 0.17.0 Parameters ---------- **kwds : optional Keyword arguments to pass on to :py:meth:`pandas.Series.plot`. Returns ------- axes : matplotlib.AxesSubplot or np.array of them """ return self(kind='box', **kwds)
def hist(self, bins=10, **kwds): """ Histogram .. versionadded:: 0.17.0 Parameters ---------- bins: integer, default 10 Number of histogram bins to be used **kwds : optional Keyword arguments to pass on to :py:meth:`pandas.Series.plot`. Returns ------- axes : matplotlib.AxesSubplot or np.array of them """ return self(kind='hist', bins=bins, **kwds)
def kde(self, **kwds): """ Kernel Density Estimate plot .. versionadded:: 0.17.0 Parameters ---------- **kwds : optional Keyword arguments to pass on to :py:meth:`pandas.Series.plot`. Returns ------- axes : matplotlib.AxesSubplot or np.array of them """ return self(kind='kde', **kwds)
def pie(self, **kwds): """ Pie chart .. versionadded:: 0.17.0 Parameters ---------- **kwds : optional Keyword arguments to pass on to :py:meth:`pandas.Series.plot`. Returns ------- axes : matplotlib.AxesSubplot or np.array of them """ return self(kind='pie', **kwds)
def line(self, x=None, y=None, **kwds): """ Line plot .. versionadded:: 0.17.0 Parameters ---------- x, y : label or position, optional Coordinates for each point. **kwds : optional Keyword arguments to pass on to :py:meth:`pandas.DataFrame.plot`. Returns ------- axes : matplotlib.AxesSubplot or np.array of them """ return self(kind='line', x=x, y=y, **kwds)
def bar(self, x=None, y=None, **kwds): """ Vertical bar plot .. versionadded:: 0.17.0 Parameters ---------- x, y : label or position, optional Coordinates for each point. **kwds : optional Keyword arguments to pass on to :py:meth:`pandas.DataFrame.plot`. Returns ------- axes : matplotlib.AxesSubplot or np.array of them """ return self(kind='bar', x=x, y=y, **kwds)
def barh(self, x=None, y=None, **kwds): """ Horizontal bar plot .. versionadded:: 0.17.0 Parameters ---------- x, y : label or position, optional Coordinates for each point. **kwds : optional Keyword arguments to pass on to :py:meth:`pandas.DataFrame.plot`. Returns ------- axes : matplotlib.AxesSubplot or np.array of them """ return self(kind='barh', x=x, y=y, **kwds)
def box(self, by=None, **kwds): """ Boxplot .. versionadded:: 0.17.0 Parameters ---------- by : string or sequence Column in the DataFrame to group by. \*\*kwds : optional Keyword arguments to pass on to :py:meth:`pandas.DataFrame.plot`. Returns ------- axes : matplotlib.AxesSubplot or np.array of them """ return self(kind='box', by=by, **kwds)
def kde(self, **kwds): """ Kernel Density Estimate plot .. versionadded:: 0.17.0 Parameters ---------- **kwds : optional Keyword arguments to pass on to :py:meth:`pandas.DataFrame.plot`. Returns ------- axes : matplotlib.AxesSubplot or np.array of them """ return self(kind='kde', **kwds)
def area(self, x=None, y=None, **kwds): """ Area plot .. versionadded:: 0.17.0 Parameters ---------- x, y : label or position, optional Coordinates for each point. **kwds : optional Keyword arguments to pass on to :py:meth:`pandas.DataFrame.plot`. Returns ------- axes : matplotlib.AxesSubplot or np.array of them """ return self(kind='area', x=x, y=y, **kwds)
def pie(self, y=None, **kwds): """ Pie chart .. versionadded:: 0.17.0 Parameters ---------- y : label or position, optional Column to plot. **kwds : optional Keyword arguments to pass on to :py:meth:`pandas.DataFrame.plot`. Returns ------- axes : matplotlib.AxesSubplot or np.array of them """ return self(kind='pie', y=y, **kwds)
def scatter(self, x, y, s=None, c=None, **kwds): """ Scatter plot .. versionadded:: 0.17.0 Parameters ---------- x, y : label or position, optional Coordinates for each point. s : scalar or array_like, optional Size of each point. c : label or position, optional Color of each point. **kwds : optional Keyword arguments to pass on to :py:meth:`pandas.DataFrame.plot`. Returns ------- axes : matplotlib.AxesSubplot or np.array of them """ return self(kind='scatter', x=x, y=y, c=c, s=s, **kwds)
def generate(self): self._args_adjust() self._compute_plot_data() self._setup_subplots() self._make_plot() self._add_table() self._make_legend() self._adorn_subplots() for ax in self.axes: self._post_plot_logic_common(ax, self.data) self._post_plot_logic(ax, self.data)
def _setup_subplots(self): if self.subplots: fig, axes = _subplots(naxes=self.nseries, sharex=self.sharex, sharey=self.sharey, figsize=self.figsize, ax=self.ax, layout=self.layout, layout_type=self._layout_type) else: if self.ax is None: fig = self.plt.figure(figsize=self.figsize) axes = fig.add_subplot(111) else: fig = self.ax.get_figure() if self.figsize is not None: fig.set_size_inches(self.figsize) axes = self.ax axes = _flatten(axes) if self.logx or self.loglog: [a.set_xscale('log') for a in axes] if self.logy or self.loglog: [a.set_yscale('log') for a in axes] self.fig = fig self.axes = axes
def _post_plot_logic(self, ax, data): """Post process for each axes. Overridden in child classes""" pass
def _adorn_subplots(self): """Common post process unrelated to data""" if len(self.axes) > 0: all_axes = self._get_subplots() nrows, ncols = self._get_axes_layout() _handle_shared_axes(axarr=all_axes, nplots=len(all_axes), naxes=nrows * ncols, nrows=nrows, ncols=ncols, sharex=self.sharex, sharey=self.sharey) for ax in self.axes: if self.yticks is not None: ax.set_yticks(self.yticks) if self.xticks is not None: ax.set_xticks(self.xticks) if self.ylim is not None: ax.set_ylim(self.ylim) if self.xlim is not None: ax.set_xlim(self.xlim) ax.grid(self.grid) if self.title: if self.subplots: self.fig.suptitle(self.title) else: self.axes[0].set_title(self.title)
def _make_legend(self): ax, leg = self._get_ax_legend(self.axes[0]) handles = [] labels = [] title = '' if not self.subplots: if leg is not None: title = leg.get_title().get_text() handles = leg.legendHandles labels = [x.get_text() for x in leg.get_texts()] if self.legend: if self.legend == 'reverse': self.legend_handles = reversed(self.legend_handles) self.legend_labels = reversed(self.legend_labels) handles += self.legend_handles labels += self.legend_labels if self.legend_title is not None: title = self.legend_title if len(handles) > 0: ax.legend(handles, labels, loc='best', title=title) elif self.subplots and self.legend: for ax in self.axes: if ax.get_visible(): ax.legend(loc='best')
def _get_ax_layer(cls, ax, primary=True): """get left (primary) or right (secondary) axes""" if primary: return getattr(ax, 'left_ax', ax) else: return getattr(ax, 'right_ax', ax)
def _get_ax(self, i): # get the twinx ax if appropriate if self.subplots: ax = self.axes[i] ax = self._maybe_right_yaxis(ax, i) self.axes[i] = ax else: ax = self.axes[0] ax = self._maybe_right_yaxis(ax, i) ax.get_yaxis().set_visible(True) return ax
def _get_axes_layout(self): axes = self._get_subplots() x_set = set() y_set = set() for ax in axes: # check axes coordinates to estimate layout points = ax.get_position().get_points() x_set.add(points[0][0]) y_set.add(points[0][1]) return (len(y_set), len(x_set))
def __init__(self, data, return_type=None, **kwargs): # Do not call LinePlot.__init__ which may fill nan if return_type not in self._valid_return_types: raise ValueError( "return_type must be {None, 'axes', 'dict', 'both'}") self.return_type = return_type MPLPlot.__init__(self, data, **kwargs)
def plot_series(data, kind='line', ax=None, # Series unique figsize=None, use_index=True, title=None, grid=None, legend=False, style=None, logx=False, logy=False, loglog=False, xticks=None, yticks=None, xlim=None, ylim=None, rot=None, fontsize=None, colormap=None, table=False, yerr=None, xerr=None, label=None, secondary_y=False, # Series unique **kwds): import matplotlib.pyplot as plt """ If no axes is specified, check whether there are existing figures If there is no existing figures, _gca() will create a figure with the default figsize, causing the figsize=parameter to be ignored. """ if ax is None and len(plt.get_fignums()) > 0: ax = _gca() ax = MPLPlot._get_ax_layer(ax) return _plot(data, kind=kind, ax=ax, figsize=figsize, use_index=use_index, title=title, grid=grid, legend=legend, style=style, logx=logx, logy=logy, loglog=loglog, xticks=xticks, yticks=yticks, xlim=xlim, ylim=ylim, rot=rot, fontsize=fontsize, colormap=colormap, table=table, yerr=yerr, xerr=xerr, label=label, secondary_y=secondary_y, **kwds)
def _grouped_plot(plotf, data, column=None, by=None, numeric_only=True, figsize=None, sharex=True, sharey=True, layout=None, rot=0, ax=None, **kwargs): from pandas import DataFrame if figsize == 'default': # allowed to specify mpl default with 'default' warnings.warn("figsize='default' is deprecated. Specify figure" "size by tuple instead", FutureWarning, stacklevel=4) figsize = None grouped = data.groupby(by) if column is not None: grouped = grouped[column] naxes = len(grouped) fig, axes = _subplots(naxes=naxes, figsize=figsize, sharex=sharex, sharey=sharey, ax=ax, layout=layout) _axes = _flatten(axes) for i, (key, group) in enumerate(grouped): ax = _axes[i] if numeric_only and isinstance(group, DataFrame): group = group._get_numeric_data() plotf(group, ax, **kwargs) ax.set_title(com.pprint_thing(key)) return fig, axes
def _grouped_plot_by_column(plotf, data, columns=None, by=None, numeric_only=True, grid=False, figsize=None, ax=None, layout=None, return_type=None, **kwargs): grouped = data.groupby(by) if columns is None: if not isinstance(by, (list, tuple)): by = [by] columns = data._get_numeric_data().columns.difference(by) naxes = len(columns) fig, axes = _subplots(naxes=naxes, sharex=True, sharey=True, figsize=figsize, ax=ax, layout=layout) _axes = _flatten(axes) result = compat.OrderedDict() for i, col in enumerate(columns): ax = _axes[i] gp_col = grouped[col] keys, values = zip(*gp_col) re_plotf = plotf(keys, values, ax, **kwargs) ax.set_title(col) ax.set_xlabel(com.pprint_thing(by)) result[col] = re_plotf ax.grid(grid) # Return axes in multiplot case, maybe revisit later # 985 if return_type is None: result = axes byline = by[0] if len(by) == 1 else by fig.suptitle('Boxplot grouped by %s' % byline) fig.subplots_adjust(bottom=0.15, top=0.9, left=0.1, right=0.9, wspace=0.2) return result
def table(ax, data, rowLabels=None, colLabels=None, **kwargs): """ Helper function to convert DataFrame and Series to matplotlib.table Parameters ---------- `ax`: Matplotlib axes object `data`: DataFrame or Series data for table contents `kwargs`: keywords, optional keyword arguments which passed to matplotlib.table.table. If `rowLabels` or `colLabels` is not specified, data index or column name will be used. Returns ------- matplotlib table object """ from pandas import DataFrame if isinstance(data, Series): data = DataFrame(data, columns=[data.name]) elif isinstance(data, DataFrame): pass else: raise ValueError('Input data must be DataFrame or Series') if rowLabels is None: rowLabels = data.index if colLabels is None: colLabels = data.columns cellText = data.values import matplotlib.table table = matplotlib.table.table(ax, cellText=cellText, rowLabels=rowLabels, colLabels=colLabels, **kwargs) return table
def _flatten(axes): if not com.is_list_like(axes): return np.array([axes]) elif isinstance(axes, (np.ndarray, Index)): return axes.ravel() return np.array(axes)
def _set_ticks_props(axes, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None): import matplotlib.pyplot as plt for ax in _flatten(axes): if xlabelsize is not None: plt.setp(ax.get_xticklabels(), fontsize=xlabelsize) if xrot is not None: plt.setp(ax.get_xticklabels(), rotation=xrot) if ylabelsize is not None: plt.setp(ax.get_yticklabels(), fontsize=ylabelsize) if yrot is not None: plt.setp(ax.get_yticklabels(), rotation=yrot) return axes
def hexbin(self, x, y, C=None, reduce_C_function=None, gridsize=None, **kwds): """ Hexbin plot .. versionadded:: 0.17.0 Parameters ---------- x, y : label or position, optional Coordinates for each point. C : label or position, optional The value at each `(x, y)` point. reduce_C_function : callable, optional Function of one argument that reduces all the values in a bin to a single number (e.g. `mean`, `max`, `sum`, `std`). gridsize : int, optional Number of bins. **kwds : optional Keyword arguments to pass on to :py:meth:`pandas.DataFrame.plot`. Returns ------- axes : matplotlib.AxesSubplot or np.array of them """ if reduce_C_function is not None: kwds['reduce_C_function'] = reduce_C_function if gridsize is not None: kwds['gridsize'] = gridsize return self(kind='hexbin', x=x, y=y, C=C, **kwds)
def rplot_ax(self, obj, *args, **kwargs): return obj.__plot__(*args, axes=self, **kwargs)
def rerrorbar_ax(self, obj, *args, **kwargs): return obj.__errorbar__(*args, axes=self, **kwargs)
def rtext_ax(self, obj, *args, **kwargs): return obj.__text__(*args, axes=self, **kwargs)
def rhist_ax(self, obj, *args, **kwargs): return draw_th1.hist(obj, *args, axes=self, **kwargs)
def rcontour_ax(self, obj, *args, **kwargs): return draw_th2.contour(obj, *args, axes=self, **kwargs)
def rpcolor_ax(self, obj, *args, **kwargs): return draw_th2.pcolor(obj, *args, axes=self, **kwargs)
def bootstrap_plot(series, fig=None, size=50, samples=500, **kwds): """Bootstrap plot. Parameters: ----------- series: Time series fig: matplotlib figure object, optional size: number of data points to consider during each sampling samples: number of times the bootstrap procedure is performed kwds: optional keyword arguments for plotting commands, must be accepted by both hist and plot Returns: -------- fig: matplotlib figure """ import random import matplotlib.pyplot as plt # random.sample(ndarray, int) fails on python 3.3, sigh data = list(series.values) samplings = [random.sample(data, size) for _ in range(samples)] means = np.array([np.mean(sampling) for sampling in samplings]) medians = np.array([np.median(sampling) for sampling in samplings]) midranges = np.array([(min(sampling) + max(sampling)) * 0.5 for sampling in samplings]) if fig is None: fig = plt.figure() x = lrange(samples) axes = [] ax1 = fig.add_subplot(2, 3, 1) ax1.set_xlabel("Sample") axes.append(ax1) ax1.plot(x, means, **kwds) ax2 = fig.add_subplot(2, 3, 2) ax2.set_xlabel("Sample") axes.append(ax2) ax2.plot(x, medians, **kwds) ax3 = fig.add_subplot(2, 3, 3) ax3.set_xlabel("Sample") axes.append(ax3) ax3.plot(x, midranges, **kwds) ax4 = fig.add_subplot(2, 3, 4) ax4.set_xlabel("Mean") axes.append(ax4) ax4.hist(means, **kwds) ax5 = fig.add_subplot(2, 3, 5) ax5.set_xlabel("Median") axes.append(ax5) ax5.hist(medians, **kwds) ax6 = fig.add_subplot(2, 3, 6) ax6.set_xlabel("Midrange") axes.append(ax6) ax6.hist(midranges, **kwds) for axis in axes: plt.setp(axis.get_xticklabels(), fontsize=8) plt.setp(axis.get_yticklabels(), fontsize=8) return fig
def _make_plot(self): x, y, c, data = self.x, self.y, self.c, self.data ax = self.axes[0] c_is_column = com.is_hashable(c) and c in self.data.columns # plot a colorbar only if a colormap is provided or necessary cb = self.kwds.pop('colorbar', self.colormap or c_is_column) # pandas uses colormap, matplotlib uses cmap. cmap = self.colormap or 'Greys' cmap = self.plt.cm.get_cmap(cmap) color = self.kwds.pop("color", None) if c is not None and color is not None: raise TypeError('Specify exactly one of `c` and `color`') elif c is None and color is None: c_values = self.plt.rcParams['patch.facecolor'] elif color is not None: c_values = color elif c_is_column: c_values = self.data[c].values else: c_values = c if self.legend and hasattr(self, 'label'): label = self.label else: label = None scatter = ax.scatter(data[x].values, data[y].values, c=c_values, label=label, cmap=cmap, **self.kwds) if cb: img = ax.collections[0] kws = dict(ax=ax) if self.mpl_ge_1_3_1(): kws['label'] = c if c_is_column else '' self.fig.colorbar(img, **kws) if label is not None: self._add_legend_handle(scatter, label) else: self.legend = False errors_x = self._get_errorbars(label=x, index=0, yerr=False) errors_y = self._get_errorbars(label=y, index=0, xerr=False) if len(errors_x) > 0 or len(errors_y) > 0: err_kwds = dict(errors_x, **errors_y) err_kwds['ecolor'] = scatter.get_facecolor()[0] ax.errorbar(data[x].values, data[y].values, linestyle='none', **err_kwds)