Python matplotlib.axes() Examples
The following are 30 code examples for showing how to use matplotlib.axes(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
You may check out the related API usage on the sidebar.
You may also want to check out all available functions/classes of the module
matplotlib
, or try the search function
.
Example 1
Project: python-control Author: python-control File: rlocus.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
def _RLClickDispatcher(event, sys, fig, ax_rlocus, plotstr, sisotool=False, bode_plot_params=None, tvect=None): """Rootlocus plot click dispatcher""" # Zoom is handled by specialized callback above, only do gain plot if event.inaxes == ax_rlocus.axes and \ plt.get_current_fig_manager().toolbar.mode not in \ {'zoom rect', 'pan/zoom'}: # if a point is clicked on the rootlocus plot visually emphasize it K = _RLFeedbackClicksPoint(event, sys, fig, ax_rlocus, sisotool) if sisotool and K is not None: _SisotoolUpdate(sys, fig, K, bode_plot_params, tvect) # Update the canvas fig.canvas.draw()
Example 2
Project: LSDMappingTools Author: LSDtopotools File: PlottingRaster.py License: MIT License | 6 votes |
def plot_filled_polygons(self,polygons, facecolour='green', edgecolour='black', linewidth=1, alpha=0.5): """ This function plots a series of shapely polygons but fills them in Args: ax_list: list of axes polygons: list of shapely polygons Author: FJC """ from shapely.geometry import Polygon from descartes import PolygonPatch from matplotlib.collections import PatchCollection print('Plotting the polygons...') #patches = [] for key, poly in polygons.items(): this_patch = PolygonPatch(poly, fc=facecolour, ec=edgecolour, alpha=alpha) self.ax_list[0].add_patch(this_patch)
Example 3
Project: Computable Author: ktraunmueller File: geo.py License: MIT License | 6 votes |
def cla(self): Axes.cla(self) self.set_longitude_grid(30) self.set_latitude_grid(15) self.set_longitude_grid_ends(75) self.xaxis.set_minor_locator(NullLocator()) self.yaxis.set_minor_locator(NullLocator()) self.xaxis.set_ticks_position('none') self.yaxis.set_ticks_position('none') self.yaxis.set_tick_params(label1On=True) # Why do we need to turn on yaxis tick labels, but # xaxis tick labels are already on? self.grid(rcParams['axes.grid']) Axes.set_xlim(self, -np.pi, np.pi) Axes.set_ylim(self, -np.pi / 2.0, np.pi / 2.0)
Example 4
Project: Computable Author: ktraunmueller File: pyplot.py License: MIT License | 6 votes |
def gca(**kwargs): """ Return the current axis instance. This can be used to control axis properties either using set or the :class:`~matplotlib.axes.Axes` methods, for example, setting the xaxis range:: plot(t,s) set(gca(), 'xlim', [0,10]) or:: plot(t,s) a = gca() a.set_xlim([0,10]) """ ax = gcf().gca(**kwargs) return ax # More ways of creating axes:
Example 5
Project: Computable Author: ktraunmueller File: pyplot.py License: MIT License | 6 votes |
def twinx(ax=None): """ Make a second axes that shares the *x*-axis. The new axes will overlay *ax* (or the current axes if *ax* is *None*). The ticks for *ax2* will be placed on the right, and the *ax2* instance is returned. .. seealso:: :file:`examples/api_examples/two_scales.py` For an example """ if ax is None: ax=gca() ax1 = ax.twinx() draw_if_interactive() return ax1
Example 6
Project: Computable Author: ktraunmueller File: pyplot.py License: MIT License | 6 votes |
def clim(vmin=None, vmax=None): """ Set the color limits of the current image. To apply clim to all axes images do:: clim(0, 0.5) If either *vmin* or *vmax* is None, the image min/max respectively will be used for color scaling. If you want to set the clim of multiple images, use, for example:: for im in gca().get_images(): im.set_clim(0, 0.05) """ im = gci() if im is None: raise RuntimeError('You must first define an image, eg with imshow') im.set_clim(vmin, vmax) draw_if_interactive()
Example 7
Project: matplotlib-4-abaqus Author: Solid-Mechanics File: geo.py License: MIT License | 6 votes |
def cla(self): Axes.cla(self) self.set_longitude_grid(30) self.set_latitude_grid(15) self.set_longitude_grid_ends(75) self.xaxis.set_minor_locator(NullLocator()) self.yaxis.set_minor_locator(NullLocator()) self.xaxis.set_ticks_position('none') self.yaxis.set_ticks_position('none') self.yaxis.set_tick_params(label1On=True) # Why do we need to turn on yaxis tick labels, but # xaxis tick labels are already on? self.grid(rcParams['axes.grid']) Axes.set_xlim(self, -np.pi, np.pi) Axes.set_ylim(self, -np.pi / 2.0, np.pi / 2.0)
Example 8
Project: matplotlib-4-abaqus Author: Solid-Mechanics File: pyplot.py License: MIT License | 6 votes |
def gca(**kwargs): """ Return the current axis instance. This can be used to control axis properties either using set or the :class:`~matplotlib.axes.Axes` methods, for example, setting the xaxis range:: plot(t,s) set(gca(), 'xlim', [0,10]) or:: plot(t,s) a = gca() a.set_xlim([0,10]) """ ax = gcf().gca(**kwargs) return ax # More ways of creating axes:
Example 9
Project: matplotlib-4-abaqus Author: Solid-Mechanics File: pyplot.py License: MIT License | 6 votes |
def twinx(ax=None): """ Make a second axes that shares the *x*-axis. The new axes will overlay *ax* (or the current axes if *ax* is *None*). The ticks for *ax2* will be placed on the right, and the *ax2* instance is returned. .. seealso:: :file:`examples/api_examples/two_scales.py` For an example """ if ax is None: ax=gca() ax1 = ax.twinx() draw_if_interactive() return ax1
Example 10
Project: matplotlib-4-abaqus Author: Solid-Mechanics File: pyplot.py License: MIT License | 6 votes |
def clim(vmin=None, vmax=None): """ Set the color limits of the current image. To apply clim to all axes images do:: clim(0, 0.5) If either *vmin* or *vmax* is None, the image min/max respectively will be used for color scaling. If you want to set the clim of multiple images, use, for example:: for im in gca().get_images(): im.set_clim(0, 0.05) """ im = gci() if im is None: raise RuntimeError('You must first define an image, eg with imshow') im.set_clim(vmin, vmax) draw_if_interactive()
Example 11
Project: neural-network-animation Author: miloharper File: geo.py License: MIT License | 6 votes |
def cla(self): Axes.cla(self) self.set_longitude_grid(30) self.set_latitude_grid(15) self.set_longitude_grid_ends(75) self.xaxis.set_minor_locator(NullLocator()) self.yaxis.set_minor_locator(NullLocator()) self.xaxis.set_ticks_position('none') self.yaxis.set_ticks_position('none') self.yaxis.set_tick_params(label1On=True) # Why do we need to turn on yaxis tick labels, but # xaxis tick labels are already on? self.grid(rcParams['axes.grid']) Axes.set_xlim(self, -np.pi, np.pi) Axes.set_ylim(self, -np.pi / 2.0, np.pi / 2.0)
Example 12
Project: neural-network-animation Author: miloharper File: test_axes.py License: MIT License | 6 votes |
def test_polar_wrap(): D2R = np.pi / 180.0 fig = plt.figure() plt.subplot(111, polar=True) plt.polar([179*D2R, -179*D2R], [0.2, 0.1], "b.-") plt.polar([179*D2R, 181*D2R], [0.2, 0.1], "g.-") plt.rgrids([0.05, 0.1, 0.15, 0.2, 0.25, 0.3]) assert len(fig.axes) == 1, 'More than one polar axes created.' fig = plt.figure() plt.subplot(111, polar=True) plt.polar([2*D2R, -2*D2R], [0.2, 0.1], "b.-") plt.polar([2*D2R, 358*D2R], [0.2, 0.1], "g.-") plt.polar([358*D2R, 2*D2R], [0.2, 0.1], "r.-") plt.rgrids([0.05, 0.1, 0.15, 0.2, 0.25, 0.3])
Example 13
Project: LSDMappingTools Author: LSDtopotools File: PlottingRaster.py License: MIT License | 5 votes |
def make_base_image(self,ax_list): """ This function creates the base image. It creates the axis for the base image, further drapes and point data are placed upon this image. Args: ax_list: A list of axes, we append the base raster to the [0] element of the axis Author: DAV and SMM """ # We need to initiate with a figure #self.ax = self.fig.add_axes([0.1,0.1,0.7,0.7]) print("This colourmap is: "+ self._RasterList[0]._colourmap) im = self.ax_list[0].imshow(self._RasterList[0]._RasterArray, self._RasterList[0]._colourmap, extent = self._RasterList[0].extents, interpolation="nearest", alpha = self._RasterList[0]._alpha) # This affects all axes because we set share_all = True. #ax.set_xlim(self._xmin,self._xmax) #ax.set_ylim(self._ymin,self._ymax) self.ax_list[0] = self.add_ticks_to_axis(self.ax_list[0]) self._drape_list.append(im) print("The number of axes are: "+str(len(self._drape_list))) print(self.ax_list[0]) return self.ax_list
Example 14
Project: LSDMappingTools Author: LSDtopotools File: PlottingRaster.py License: MIT License | 5 votes |
def add_drape_image(self,RasterName,Directory,colourmap = "gray", alpha=0.5, show_colourbar = False, colorbarlabel = "Colourbar", discrete_cmap=False, n_colours=10, norm = "None", colour_min_max = [], modify_raster_values=False, old_values=[], new_values=[], cbar_type=float, NFF_opti = False, custom_min_max = [], zorder=1): """ This function adds a drape over the base raster. Args: RasterName (string): The name of the raster (no directory, but need extension) Directory (string): directory of the data colourmap (string or colourmap): The colourmap. Can be a strong for default colourmaps alpha (float): The transparency of the drape (1 is opaque, 0 totally transparent) show_colourbar (bool): True to show colourbar colourbarlabel (string): The label of the colourbar discrete_cmap (bool): If true, make discrete values for colours, otherwise a gradient. n_colours (int): number of colours in discrete colourbar norm (string): Normalisation of colourbar. I don't understand this so don't change colour_min_max( list of int/float): if it contains two elements, map the colourbar between these two values. modify_raster_values (bool): If true, it takes old_values in list and replaces them with new_values old_values (list): A list of values to be replaced in raster. Useful for masking and renaming new_values (list): A list of the new values. This probably should be done with a map: TODO cbar_type (type): Sets the type of the colourbar (if you want int labels, set to int) NFF_opti (bool): If true, uses the new file loading functions. It is faster but hasn't been completely tested. custom_min_max (list of int/float): if it contains two elements, recast the raster to [min,max] values for display. Author: SMM """ print("N axes are: "+str(len(self.ax_list))) print(self.ax_list[0]) self.ax_list = self._add_drape_image(self.ax_list,RasterName,Directory,colourmap,alpha, colorbarlabel,discrete_cmap,n_colours, norm, colour_min_max,modify_raster_values,old_values, new_values,cbar_type, NFF_opti, custom_min_max, zorder=zorder) #print("Getting axis limits in drape function: ") #print(self.ax_list[0].get_xlim())
Example 15
Project: LSDMappingTools Author: LSDtopotools File: PlottingRaster.py License: MIT License | 5 votes |
def add_point_colourbar(self,ax_list,sc,cmap = "cubehelix",colorbarlabel = "Colourbar", discrete=False, n_colours=10, cbar_type=float): """ This adds a colourbar for any points that are on the DEM. Args: ax_list: The list of axes objects. Assumes colourbar is in axis_list[-1] sc: The scatterplot object. Generated by plt.scatter cmap (string or colourmap): The colourmap. colorbarlabel (string): The label of the colourbar Author: SMM """ fig = matplotlib.pyplot.gcf() ax_list.append(fig.add_axes([0.1,0.8,0.2,0.5])) cbar = plt.colorbar(sc,cmap=cmap, orientation=self.colourbar_orientation,cax=ax_list[-1]) if self.colourbar_location == 'top': ax_list[-1].set_xlabel(colorbarlabel, fontname='Liberation Sans',labelpad=5) elif self.colourbar_location == 'bottom': ax_list[-1].set_xlabel(colorbarlabel, fontname='Liberation Sans',labelpad=5) elif self.colourbar_location == 'left': ax_list[-1].set_ylabel(colorbarlabel, fontname='Liberation Sans',labelpad=-75,rotation=90) elif self.colourbar_location == 'right': ax_list[-1].set_ylabel(colorbarlabel, fontname='Liberation Sans',labelpad=10,rotation=270) return ax_list
Example 16
Project: Computable Author: ktraunmueller File: gridspec.py License: MIT License | 5 votes |
def update(self, **kwargs): """ Update the current values. If any kwarg is None, default to the current value, if set, otherwise to rc. """ for k, v in kwargs.iteritems(): if k in self._AllowedKeys: setattr(self, k, v) else: raise AttributeError("%s is unknown keyword" % (k,)) from matplotlib import _pylab_helpers from matplotlib.axes import SubplotBase for figmanager in _pylab_helpers.Gcf.figs.itervalues(): for ax in figmanager.canvas.figure.axes: # copied from Figure.subplots_adjust if not isinstance(ax, SubplotBase): # Check if sharing a subplots axis if ax._sharex is not None and isinstance(ax._sharex, SubplotBase): if ax._sharex.get_subplotspec().get_gridspec() == self: ax._sharex.update_params() ax.set_position(ax._sharex.figbox) elif ax._sharey is not None and isinstance(ax._sharey,SubplotBase): if ax._sharey.get_subplotspec().get_gridspec() == self: ax._sharey.update_params() ax.set_position(ax._sharey.figbox) else: ss = ax.get_subplotspec().get_topmost_subplotspec() if ss.get_gridspec() == self: ax.update_params() ax.set_position(ax.figbox)
Example 17
Project: Computable Author: ktraunmueller File: gridspec.py License: MIT License | 5 votes |
def tight_layout(self, fig, renderer=None, pad=1.08, h_pad=None, w_pad=None, rect=None): """ Adjust subplot parameters to give specified padding. Parameters: pad : float padding between the figure edge and the edges of subplots, as a fraction of the font-size. h_pad, w_pad : float padding (height/width) between edges of adjacent subplots. Defaults to `pad_inches`. rect : if rect is given, it is interpreted as a rectangle (left, bottom, right, top) in the normalized figure coordinate that the whole subplots area (including labels) will fit into. Default is (0, 0, 1, 1). """ from tight_layout import (get_subplotspec_list, get_tight_layout_figure, get_renderer) subplotspec_list = get_subplotspec_list(fig.axes, grid_spec=self) if None in subplotspec_list: warnings.warn("This figure includes Axes that are not " "compatible with tight_layout, so its " "results might be incorrect.") if renderer is None: renderer = get_renderer(fig) kwargs = get_tight_layout_figure(fig, fig.axes, subplotspec_list, renderer, pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect, ) self.update(**kwargs)
Example 18
Project: Computable Author: ktraunmueller File: geo.py License: MIT License | 5 votes |
def set_xlim(self, *args, **kwargs): raise TypeError("It is not possible to change axes limits " "for geographic projections. Please consider " "using Basemap or Cartopy.")
Example 19
Project: Computable Author: ktraunmueller File: geo.py License: MIT License | 5 votes |
def can_zoom(self): """ Return *True* if this axes supports the zoom box button functionality. This axes object does not support interactive zoom box. """ return False
Example 20
Project: Computable Author: ktraunmueller File: polar.py License: MIT License | 5 votes |
def _init_axis(self): "move this out of __init__ because non-separable axes don't use it" self.xaxis = maxis.XAxis(self) self.yaxis = maxis.YAxis(self) # Calling polar_axes.xaxis.cla() or polar_axes.xaxis.cla() # results in weird artifacts. Therefore we disable this for # now. # self.spines['polar'].register_axis(self.yaxis) self._update_transScale()
Example 21
Project: Computable Author: ktraunmueller File: polar.py License: MIT License | 5 votes |
def set_thetagrids(self, angles, labels=None, frac=None, fmt=None, **kwargs): """ Set the angles at which to place the theta grids (these gridlines are equal along the theta dimension). *angles* is in degrees. *labels*, if not None, is a ``len(angles)`` list of strings of the labels to use at each angle. If *labels* is None, the labels will be ``fmt %% angle`` *frac* is the fraction of the polar axes radius at which to place the label (1 is the edge). e.g., 1.05 is outside the axes and 0.95 is inside the axes. Return value is a list of tuples (*line*, *label*), where *line* is :class:`~matplotlib.lines.Line2D` instances and the *label* is :class:`~matplotlib.text.Text` instances. kwargs are optional text properties for the labels: %(Text)s ACCEPTS: sequence of floats """ # Make sure we take into account unitized data angles = self.convert_yunits(angles) angles = np.asarray(angles, np.float_) self.set_xticks(angles * (np.pi / 180.0)) if labels is not None: self.set_xticklabels(labels) elif fmt is not None: self.xaxis.set_major_formatter(FormatStrFormatter(fmt)) if frac is not None: self._theta_label1_position.clear().translate(0.0, frac) self._theta_label2_position.clear().translate(0.0, 1.0 / frac) for t in self.xaxis.get_ticklabels(): t.update(kwargs) return self.xaxis.get_ticklines(), self.xaxis.get_ticklabels()
Example 22
Project: Computable Author: ktraunmueller File: polar.py License: MIT License | 5 votes |
def can_zoom(self): """ Return *True* if this axes supports the zoom box button functionality. Polar axes do not support zoom boxes. """ return False
Example 23
Project: Computable Author: ktraunmueller File: polar.py License: MIT License | 5 votes |
def can_pan(self) : """ Return *True* if this axes supports the pan/zoom button functionality. For polar axes, this is slightly misleading. Both panning and zooming are performed by the same button. Panning is performed in azimuth while zooming is done along the radial. """ return True
Example 24
Project: Computable Author: ktraunmueller File: pyplot.py License: MIT License | 5 votes |
def sci(im): """ Set the current image. This image will be the target of colormap commands like :func:`~matplotlib.pyplot.jet`, :func:`~matplotlib.pyplot.hot` or :func:`~matplotlib.pyplot.clim`). The current image is an attribute of the current axes. """ gca()._sci(im) ## Any Artist ## # (getp is simply imported)
Example 25
Project: Computable Author: ktraunmueller File: pyplot.py License: MIT License | 5 votes |
def hold(b=None): """ Set the hold state. If *b* is None (default), toggle the hold state, else set the hold state to boolean value *b*:: hold() # toggle hold hold(True) # hold is on hold(False) # hold is off When *hold* is *True*, subsequent plot commands will be added to the current axes. When *hold* is *False*, the current axes and figure will be cleared on the next plot command. """ fig = gcf() ax = fig.gca() fig.hold(b) ax.hold(b) # b=None toggles the hold state, so let's get get the current hold # state; but should pyplot hold toggle the rc setting - me thinks # not b = ax.ishold() rc('axes', hold=b)
Example 26
Project: Computable Author: ktraunmueller File: pyplot.py License: MIT License | 5 votes |
def ishold(): """ Return the hold status of the current axes. """ return gca().ishold()
Example 27
Project: Computable Author: ktraunmueller File: pyplot.py License: MIT License | 5 votes |
def sca(ax): """ Set the current Axes instance to *ax*. The current Figure is updated to the parent of *ax*. """ managers = _pylab_helpers.Gcf.get_all_fig_managers() for m in managers: if ax in m.canvas.figure.axes: _pylab_helpers.Gcf.set_active(m) m.canvas.figure.sca(ax) return raise ValueError("Axes instance argument was not found in a figure.")
Example 28
Project: Computable Author: ktraunmueller File: pyplot.py License: MIT License | 5 votes |
def subplot2grid(shape, loc, rowspan=1, colspan=1, **kwargs): """ Create a subplot in a grid. The grid is specified by *shape*, at location of *loc*, spanning *rowspan*, *colspan* cells in each direction. The index for loc is 0-based. :: subplot2grid(shape, loc, rowspan=1, colspan=1) is identical to :: gridspec=GridSpec(shape[0], shape[2]) subplotspec=gridspec.new_subplotspec(loc, rowspan, colspan) subplot(subplotspec) """ fig = gcf() s1, s2 = shape subplotspec = GridSpec(s1, s2).new_subplotspec(loc, rowspan=rowspan, colspan=colspan) a = fig.add_subplot(subplotspec, **kwargs) bbox = a.bbox byebye = [] for other in fig.axes: if other==a: continue if bbox.fully_overlaps(other.bbox): byebye.append(other) for ax in byebye: delaxes(ax) draw_if_interactive() return a
Example 29
Project: Computable Author: ktraunmueller File: pyplot.py License: MIT License | 5 votes |
def twiny(ax=None): """ Make a second axes that shares the *y*-axis. The new axis will overlay *ax* (or the current axes if *ax* is *None*). The ticks for *ax2* will be placed on the top, and the *ax2* instance is returned. """ if ax is None: ax=gca() ax1 = ax.twiny() draw_if_interactive() return ax1
Example 30
Project: Computable Author: ktraunmueller File: pyplot.py License: MIT License | 5 votes |
def xlim(*args, **kwargs): """ Get or set the *x* limits of the current axes. :: xmin, xmax = xlim() # return the current xlim xlim( (xmin, xmax) ) # set the xlim to xmin, xmax xlim( xmin, xmax ) # set the xlim to xmin, xmax If you do not specify args, you can pass the xmin and xmax as kwargs, e.g.:: xlim(xmax=3) # adjust the max leaving min unchanged xlim(xmin=1) # adjust the min leaving max unchanged Setting limits turns autoscaling off for the x-axis. The new axis limits are returned as a length 2 tuple. """ ax = gca() if not args and not kwargs: return ax.get_xlim() ret = ax.set_xlim(*args, **kwargs) draw_if_interactive() return ret