You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3296 lines
108 KiB

4 years ago
  1. # Note: The first part of this file can be modified in place, but the latter
  2. # part is autogenerated by the boilerplate.py script.
  3. """
  4. `matplotlib.pyplot` is a state-based interface to matplotlib. It provides
  5. a MATLAB-like way of plotting.
  6. pyplot is mainly intended for interactive plots and simple cases of programmatic
  7. plot generation::
  8. import numpy as np
  9. import matplotlib.pyplot as plt
  10. x = np.arange(0, 5, 0.1)
  11. y = np.sin(x)
  12. plt.plot(x, y)
  13. The object-oriented API is recommended for more complex plots.
  14. """
  15. import importlib
  16. import inspect
  17. import logging
  18. from numbers import Number
  19. import re
  20. import sys
  21. import time
  22. import warnings
  23. from cycler import cycler
  24. import matplotlib
  25. import matplotlib.colorbar
  26. import matplotlib.image
  27. from matplotlib import rcsetup, style
  28. from matplotlib import _pylab_helpers, interactive
  29. from matplotlib.cbook import (
  30. dedent, deprecated, silent_list, warn_deprecated, _string_to_bool)
  31. from matplotlib import docstring
  32. from matplotlib.backend_bases import FigureCanvasBase
  33. from matplotlib.figure import Figure, figaspect
  34. from matplotlib.gridspec import GridSpec
  35. from matplotlib import rcParams, rcParamsDefault, get_backend, rcParamsOrig
  36. from matplotlib import rc_context
  37. from matplotlib.rcsetup import interactive_bk as _interactive_bk
  38. from matplotlib.artist import getp, get, Artist
  39. from matplotlib.artist import setp as _setp
  40. from matplotlib.axes import Axes, Subplot
  41. from matplotlib.projections import PolarAxes
  42. from matplotlib import mlab # for csv2rec, detrend_none, window_hanning
  43. from matplotlib.scale import get_scale_docs, get_scale_names
  44. from matplotlib import cm
  45. from matplotlib.cm import get_cmap, register_cmap
  46. import numpy as np
  47. # We may not need the following imports here:
  48. from matplotlib.colors import Normalize
  49. from matplotlib.lines import Line2D
  50. from matplotlib.text import Text, Annotation
  51. from matplotlib.patches import Polygon, Rectangle, Circle, Arrow
  52. from matplotlib.widgets import SubplotTool, Button, Slider, Widget
  53. from .ticker import TickHelper, Formatter, FixedFormatter, NullFormatter,\
  54. FuncFormatter, FormatStrFormatter, ScalarFormatter,\
  55. LogFormatter, LogFormatterExponent, LogFormatterMathtext,\
  56. Locator, IndexLocator, FixedLocator, NullLocator,\
  57. LinearLocator, LogLocator, AutoLocator, MultipleLocator,\
  58. MaxNLocator
  59. from matplotlib.backends import pylab_setup, _get_running_interactive_framework
  60. _log = logging.getLogger(__name__)
  61. ## Global ##
  62. _IP_REGISTERED = None
  63. _INSTALL_FIG_OBSERVER = False
  64. def install_repl_displayhook():
  65. """
  66. Install a repl display hook so that any stale figure are automatically
  67. redrawn when control is returned to the repl.
  68. This works both with IPython and with vanilla python shells.
  69. """
  70. global _IP_REGISTERED
  71. global _INSTALL_FIG_OBSERVER
  72. class _NotIPython(Exception):
  73. pass
  74. # see if we have IPython hooks around, if use them
  75. try:
  76. if 'IPython' in sys.modules:
  77. from IPython import get_ipython
  78. ip = get_ipython()
  79. if ip is None:
  80. raise _NotIPython()
  81. if _IP_REGISTERED:
  82. return
  83. def post_execute():
  84. if matplotlib.is_interactive():
  85. draw_all()
  86. # IPython >= 2
  87. try:
  88. ip.events.register('post_execute', post_execute)
  89. except AttributeError:
  90. # IPython 1.x
  91. ip.register_post_execute(post_execute)
  92. _IP_REGISTERED = post_execute
  93. _INSTALL_FIG_OBSERVER = False
  94. # trigger IPython's eventloop integration, if available
  95. from IPython.core.pylabtools import backend2gui
  96. ipython_gui_name = backend2gui.get(get_backend())
  97. if ipython_gui_name:
  98. ip.enable_gui(ipython_gui_name)
  99. else:
  100. _INSTALL_FIG_OBSERVER = True
  101. # import failed or ipython is not running
  102. except (ImportError, _NotIPython):
  103. _INSTALL_FIG_OBSERVER = True
  104. def uninstall_repl_displayhook():
  105. """
  106. Uninstall the matplotlib display hook.
  107. .. warning
  108. Need IPython >= 2 for this to work. For IPython < 2 will raise a
  109. ``NotImplementedError``
  110. .. warning
  111. If you are using vanilla python and have installed another
  112. display hook this will reset ``sys.displayhook`` to what ever
  113. function was there when matplotlib installed it's displayhook,
  114. possibly discarding your changes.
  115. """
  116. global _IP_REGISTERED
  117. global _INSTALL_FIG_OBSERVER
  118. if _IP_REGISTERED:
  119. from IPython import get_ipython
  120. ip = get_ipython()
  121. try:
  122. ip.events.unregister('post_execute', _IP_REGISTERED)
  123. except AttributeError:
  124. raise NotImplementedError("Can not unregister events "
  125. "in IPython < 2.0")
  126. _IP_REGISTERED = None
  127. if _INSTALL_FIG_OBSERVER:
  128. _INSTALL_FIG_OBSERVER = False
  129. draw_all = _pylab_helpers.Gcf.draw_all
  130. @docstring.copy_dedent(Artist.findobj)
  131. def findobj(o=None, match=None, include_self=True):
  132. if o is None:
  133. o = gcf()
  134. return o.findobj(match, include_self=include_self)
  135. def switch_backend(newbackend):
  136. """
  137. Close all open figures and set the Matplotlib backend.
  138. The argument is case-insensitive. Switching to an interactive backend is
  139. possible only if no event loop for another interactive backend has started.
  140. Switching to and from non-interactive backends is always possible.
  141. Parameters
  142. ----------
  143. newbackend : str
  144. The name of the backend to use.
  145. """
  146. close("all")
  147. if newbackend is rcsetup._auto_backend_sentinel:
  148. for candidate in ["macosx", "qt5agg", "qt4agg", "gtk3agg", "gtk3cairo",
  149. "tkagg", "wxagg", "agg", "cairo"]:
  150. try:
  151. switch_backend(candidate)
  152. except ImportError:
  153. continue
  154. else:
  155. rcParamsOrig['backend'] = candidate
  156. return
  157. backend_name = (
  158. newbackend[9:] if newbackend.startswith("module://")
  159. else "matplotlib.backends.backend_{}".format(newbackend.lower()))
  160. backend_mod = importlib.import_module(backend_name)
  161. Backend = type(
  162. "Backend", (matplotlib.backends._Backend,), vars(backend_mod))
  163. _log.debug("Loaded backend %s version %s.",
  164. newbackend, Backend.backend_version)
  165. required_framework = Backend.required_interactive_framework
  166. if required_framework is not None:
  167. current_framework = \
  168. matplotlib.backends._get_running_interactive_framework()
  169. if (current_framework and required_framework
  170. and current_framework != required_framework):
  171. raise ImportError(
  172. "Cannot load backend {!r} which requires the {!r} interactive "
  173. "framework, as {!r} is currently running".format(
  174. newbackend, required_framework, current_framework))
  175. rcParams['backend'] = rcParamsDefault['backend'] = newbackend
  176. global _backend_mod, new_figure_manager, draw_if_interactive, _show
  177. _backend_mod = backend_mod
  178. new_figure_manager = Backend.new_figure_manager
  179. draw_if_interactive = Backend.draw_if_interactive
  180. _show = Backend.show
  181. # Need to keep a global reference to the backend for compatibility reasons.
  182. # See https://github.com/matplotlib/matplotlib/issues/6092
  183. matplotlib.backends.backend = newbackend
  184. def show(*args, **kw):
  185. """
  186. Display a figure.
  187. When running in ipython with its pylab mode, display all
  188. figures and return to the ipython prompt.
  189. In non-interactive mode, display all figures and block until
  190. the figures have been closed; in interactive mode it has no
  191. effect unless figures were created prior to a change from
  192. non-interactive to interactive mode (not recommended). In
  193. that case it displays the figures but does not block.
  194. A single experimental keyword argument, *block*, may be
  195. set to True or False to override the blocking behavior
  196. described above.
  197. """
  198. global _show
  199. return _show(*args, **kw)
  200. def isinteractive():
  201. """Return the status of interactive mode."""
  202. return matplotlib.is_interactive()
  203. def ioff():
  204. """Turn the interactive mode off."""
  205. matplotlib.interactive(False)
  206. uninstall_repl_displayhook()
  207. def ion():
  208. """Turn the interactive mode on."""
  209. matplotlib.interactive(True)
  210. install_repl_displayhook()
  211. def pause(interval):
  212. """
  213. Pause for *interval* seconds.
  214. If there is an active figure, it will be updated and displayed before the
  215. pause, and the GUI event loop (if any) will run during the pause.
  216. This can be used for crude animation. For more complex animation, see
  217. :mod:`matplotlib.animation`.
  218. Notes
  219. -----
  220. This function is experimental; its behavior may be changed or extended in a
  221. future release.
  222. """
  223. manager = _pylab_helpers.Gcf.get_active()
  224. if manager is not None:
  225. canvas = manager.canvas
  226. if canvas.figure.stale:
  227. canvas.draw_idle()
  228. show(block=False)
  229. canvas.start_event_loop(interval)
  230. else:
  231. time.sleep(interval)
  232. @docstring.copy_dedent(matplotlib.rc)
  233. def rc(group, **kwargs):
  234. matplotlib.rc(group, **kwargs)
  235. @docstring.copy_dedent(matplotlib.rc_context)
  236. def rc_context(rc=None, fname=None):
  237. return matplotlib.rc_context(rc, fname)
  238. @docstring.copy_dedent(matplotlib.rcdefaults)
  239. def rcdefaults():
  240. matplotlib.rcdefaults()
  241. if matplotlib.is_interactive():
  242. draw_all()
  243. ## Current image ##
  244. def gci():
  245. """
  246. Get the current colorable artist. Specifically, returns the
  247. current :class:`~matplotlib.cm.ScalarMappable` instance (image or
  248. patch collection), or *None* if no images or patch collections
  249. have been defined. The commands :func:`~matplotlib.pyplot.imshow`
  250. and :func:`~matplotlib.pyplot.figimage` create
  251. :class:`~matplotlib.image.Image` instances, and the commands
  252. :func:`~matplotlib.pyplot.pcolor` and
  253. :func:`~matplotlib.pyplot.scatter` create
  254. :class:`~matplotlib.collections.Collection` instances. The
  255. current image is an attribute of the current axes, or the nearest
  256. earlier axes in the current figure that contains an image.
  257. """
  258. return gcf()._gci()
  259. ## Any Artist ##
  260. # (getp is simply imported)
  261. @docstring.copy(_setp)
  262. def setp(obj, *args, **kwargs):
  263. return _setp(obj, *args, **kwargs)
  264. def xkcd(scale=1, length=100, randomness=2):
  265. """
  266. Turn on `xkcd <https://xkcd.com/>`_ sketch-style drawing mode.
  267. This will only have effect on things drawn after this function is
  268. called.
  269. For best results, the "Humor Sans" font should be installed: it is
  270. not included with matplotlib.
  271. Parameters
  272. ----------
  273. scale : float, optional
  274. The amplitude of the wiggle perpendicular to the source line.
  275. length : float, optional
  276. The length of the wiggle along the line.
  277. randomness : float, optional
  278. The scale factor by which the length is shrunken or expanded.
  279. Notes
  280. -----
  281. This function works by a number of rcParams, so it will probably
  282. override others you have set before.
  283. If you want the effects of this function to be temporary, it can
  284. be used as a context manager, for example::
  285. with plt.xkcd():
  286. # This figure will be in XKCD-style
  287. fig1 = plt.figure()
  288. # ...
  289. # This figure will be in regular style
  290. fig2 = plt.figure()
  291. """
  292. if rcParams['text.usetex']:
  293. raise RuntimeError(
  294. "xkcd mode is not compatible with text.usetex = True")
  295. from matplotlib import patheffects
  296. return rc_context({
  297. 'font.family': ['xkcd', 'Humor Sans', 'Comic Sans MS'],
  298. 'font.size': 14.0,
  299. 'path.sketch': (scale, length, randomness),
  300. 'path.effects': [patheffects.withStroke(linewidth=4, foreground="w")],
  301. 'axes.linewidth': 1.5,
  302. 'lines.linewidth': 2.0,
  303. 'figure.facecolor': 'white',
  304. 'grid.linewidth': 0.0,
  305. 'axes.grid': False,
  306. 'axes.unicode_minus': False,
  307. 'axes.edgecolor': 'black',
  308. 'xtick.major.size': 8,
  309. 'xtick.major.width': 3,
  310. 'ytick.major.size': 8,
  311. 'ytick.major.width': 3,
  312. })
  313. ## Figures ##
  314. def figure(num=None, # autoincrement if None, else integer from 1-N
  315. figsize=None, # defaults to rc figure.figsize
  316. dpi=None, # defaults to rc figure.dpi
  317. facecolor=None, # defaults to rc figure.facecolor
  318. edgecolor=None, # defaults to rc figure.edgecolor
  319. frameon=True,
  320. FigureClass=Figure,
  321. clear=False,
  322. **kwargs
  323. ):
  324. """
  325. Create a new figure.
  326. Parameters
  327. ----------
  328. num : integer or string, optional, default: None
  329. If not provided, a new figure will be created, and the figure number
  330. will be incremented. The figure objects holds this number in a `number`
  331. attribute.
  332. If num is provided, and a figure with this id already exists, make
  333. it active, and returns a reference to it. If this figure does not
  334. exists, create it and returns it.
  335. If num is a string, the window title will be set to this figure's
  336. `num`.
  337. figsize : tuple of integers, optional, default: None
  338. width, height in inches. If not provided, defaults to
  339. :rc:`figure.figsize` = ``[6.4, 4.8]``.
  340. dpi : integer, optional, default: None
  341. resolution of the figure. If not provided, defaults to
  342. :rc:`figure.dpi` = ``100``.
  343. facecolor :
  344. the background color. If not provided, defaults to
  345. :rc:`figure.facecolor` = ``'w'``.
  346. edgecolor :
  347. the border color. If not provided, defaults to
  348. :rc:`figure.edgecolor` = ``'w'``.
  349. frameon : bool, optional, default: True
  350. If False, suppress drawing the figure frame.
  351. FigureClass : subclass of `~matplotlib.figure.Figure`
  352. Optionally use a custom `.Figure` instance.
  353. clear : bool, optional, default: False
  354. If True and the figure already exists, then it is cleared.
  355. Returns
  356. -------
  357. figure : `~matplotlib.figure.Figure`
  358. The `.Figure` instance returned will also be passed to new_figure_manager
  359. in the backends, which allows to hook custom `.Figure` classes into the
  360. pyplot interface. Additional kwargs will be passed to the `.Figure`
  361. init function.
  362. Notes
  363. -----
  364. If you are creating many figures, make sure you explicitly call
  365. :func:`.pyplot.close` on the figures you are not using, because this will
  366. enable pyplot to properly clean up the memory.
  367. `~matplotlib.rcParams` defines the default values, which can be modified
  368. in the matplotlibrc file.
  369. """
  370. if figsize is None:
  371. figsize = rcParams['figure.figsize']
  372. if dpi is None:
  373. dpi = rcParams['figure.dpi']
  374. if facecolor is None:
  375. facecolor = rcParams['figure.facecolor']
  376. if edgecolor is None:
  377. edgecolor = rcParams['figure.edgecolor']
  378. allnums = get_fignums()
  379. next_num = max(allnums) + 1 if allnums else 1
  380. figLabel = ''
  381. if num is None:
  382. num = next_num
  383. elif isinstance(num, str):
  384. figLabel = num
  385. allLabels = get_figlabels()
  386. if figLabel not in allLabels:
  387. if figLabel == 'all':
  388. warnings.warn("close('all') closes all existing figures")
  389. num = next_num
  390. else:
  391. inum = allLabels.index(figLabel)
  392. num = allnums[inum]
  393. else:
  394. num = int(num) # crude validation of num argument
  395. figManager = _pylab_helpers.Gcf.get_fig_manager(num)
  396. if figManager is None:
  397. max_open_warning = rcParams['figure.max_open_warning']
  398. if len(allnums) >= max_open_warning >= 1:
  399. warnings.warn(
  400. "More than %d figures have been opened. Figures "
  401. "created through the pyplot interface "
  402. "(`matplotlib.pyplot.figure`) are retained until "
  403. "explicitly closed and may consume too much memory. "
  404. "(To control this warning, see the rcParam "
  405. "`figure.max_open_warning`)." %
  406. max_open_warning, RuntimeWarning)
  407. if get_backend().lower() == 'ps':
  408. dpi = 72
  409. figManager = new_figure_manager(num, figsize=figsize,
  410. dpi=dpi,
  411. facecolor=facecolor,
  412. edgecolor=edgecolor,
  413. frameon=frameon,
  414. FigureClass=FigureClass,
  415. **kwargs)
  416. if figLabel:
  417. figManager.set_window_title(figLabel)
  418. figManager.canvas.figure.set_label(figLabel)
  419. # make this figure current on button press event
  420. def make_active(event):
  421. _pylab_helpers.Gcf.set_active(figManager)
  422. cid = figManager.canvas.mpl_connect('button_press_event', make_active)
  423. figManager._cidgcf = cid
  424. _pylab_helpers.Gcf.set_active(figManager)
  425. fig = figManager.canvas.figure
  426. fig.number = num
  427. # make sure backends (inline) that we don't ship that expect this
  428. # to be called in plotting commands to make the figure call show
  429. # still work. There is probably a better way to do this in the
  430. # FigureManager base class.
  431. if matplotlib.is_interactive():
  432. draw_if_interactive()
  433. if _INSTALL_FIG_OBSERVER:
  434. fig.stale_callback = _auto_draw_if_interactive
  435. if clear:
  436. figManager.canvas.figure.clear()
  437. return figManager.canvas.figure
  438. def _auto_draw_if_interactive(fig, val):
  439. """
  440. This is an internal helper function for making sure that auto-redrawing
  441. works as intended in the plain python repl.
  442. Parameters
  443. ----------
  444. fig : Figure
  445. A figure object which is assumed to be associated with a canvas
  446. """
  447. if val and matplotlib.is_interactive() and not fig.canvas.is_saving():
  448. fig.canvas.draw_idle()
  449. def gcf():
  450. """Get a reference to the current figure."""
  451. figManager = _pylab_helpers.Gcf.get_active()
  452. if figManager is not None:
  453. return figManager.canvas.figure
  454. else:
  455. return figure()
  456. def fignum_exists(num):
  457. """Return whether the figure with the given id exists."""
  458. return _pylab_helpers.Gcf.has_fignum(num) or num in get_figlabels()
  459. def get_fignums():
  460. """Return a list of existing figure numbers."""
  461. return sorted(_pylab_helpers.Gcf.figs)
  462. def get_figlabels():
  463. """Return a list of existing figure labels."""
  464. figManagers = _pylab_helpers.Gcf.get_all_fig_managers()
  465. figManagers.sort(key=lambda m: m.num)
  466. return [m.canvas.figure.get_label() for m in figManagers]
  467. def get_current_fig_manager():
  468. """
  469. Return the figure manager of the active figure.
  470. If there is currently no active figure, a new one is created.
  471. """
  472. figManager = _pylab_helpers.Gcf.get_active()
  473. if figManager is None:
  474. gcf() # creates an active figure as a side effect
  475. figManager = _pylab_helpers.Gcf.get_active()
  476. return figManager
  477. @docstring.copy_dedent(FigureCanvasBase.mpl_connect)
  478. def connect(s, func):
  479. return get_current_fig_manager().canvas.mpl_connect(s, func)
  480. @docstring.copy_dedent(FigureCanvasBase.mpl_disconnect)
  481. def disconnect(cid):
  482. return get_current_fig_manager().canvas.mpl_disconnect(cid)
  483. def close(fig=None):
  484. """
  485. Close a figure window.
  486. Parameters
  487. ----------
  488. fig : None or int or str or `.Figure`
  489. The figure to close. There are a number of ways to specify this:
  490. - *None*: the current figure
  491. - `.Figure`: the given `.Figure` instance
  492. - ``int``: a figure number
  493. - ``str``: a figure name
  494. - 'all': all figures
  495. """
  496. if fig is None:
  497. figManager = _pylab_helpers.Gcf.get_active()
  498. if figManager is None:
  499. return
  500. else:
  501. _pylab_helpers.Gcf.destroy(figManager.num)
  502. elif fig == 'all':
  503. _pylab_helpers.Gcf.destroy_all()
  504. elif isinstance(fig, int):
  505. _pylab_helpers.Gcf.destroy(fig)
  506. elif hasattr(fig, 'int'):
  507. # if we are dealing with a type UUID, we
  508. # can use its integer representation
  509. _pylab_helpers.Gcf.destroy(fig.int)
  510. elif isinstance(fig, str):
  511. allLabels = get_figlabels()
  512. if fig in allLabels:
  513. num = get_fignums()[allLabels.index(fig)]
  514. _pylab_helpers.Gcf.destroy(num)
  515. elif isinstance(fig, Figure):
  516. _pylab_helpers.Gcf.destroy_fig(fig)
  517. else:
  518. raise TypeError("close() argument must be a Figure, an int, a string, "
  519. "or None, not '%s'")
  520. def clf():
  521. """Clear the current figure."""
  522. gcf().clf()
  523. def draw():
  524. """Redraw the current figure.
  525. This is used to update a figure that has been altered, but not
  526. automatically re-drawn. If interactive mode is on (:func:`.ion()`), this
  527. should be only rarely needed, but there may be ways to modify the state of
  528. a figure without marking it as `stale`. Please report these cases as
  529. bugs.
  530. A more object-oriented alternative, given any
  531. :class:`~matplotlib.figure.Figure` instance, :attr:`fig`, that
  532. was created using a :mod:`~matplotlib.pyplot` function, is::
  533. fig.canvas.draw_idle()
  534. """
  535. get_current_fig_manager().canvas.draw_idle()
  536. @docstring.copy_dedent(Figure.savefig)
  537. def savefig(*args, **kwargs):
  538. fig = gcf()
  539. res = fig.savefig(*args, **kwargs)
  540. fig.canvas.draw_idle() # need this if 'transparent=True' to reset colors
  541. return res
  542. @docstring.copy_dedent(Figure.ginput)
  543. def ginput(*args, **kwargs):
  544. """
  545. Blocking call to interact with the figure.
  546. This will wait for *n* clicks from the user and return a list of the
  547. coordinates of each click.
  548. If *timeout* is negative, does not timeout.
  549. """
  550. return gcf().ginput(*args, **kwargs)
  551. @docstring.copy_dedent(Figure.waitforbuttonpress)
  552. def waitforbuttonpress(*args, **kwargs):
  553. """
  554. Blocking call to interact with the figure.
  555. This will wait for *n* key or mouse clicks from the user and
  556. return a list containing True's for keyboard clicks and False's
  557. for mouse clicks.
  558. If *timeout* is negative, does not timeout.
  559. """
  560. return gcf().waitforbuttonpress(*args, **kwargs)
  561. ## Putting things in figures ##
  562. @docstring.copy_dedent(Figure.text)
  563. def figtext(x, y, s, *args, **kwargs):
  564. return gcf().text(x, y, s, *args, **kwargs)
  565. @docstring.copy_dedent(Figure.suptitle)
  566. def suptitle(t, **kwargs):
  567. return gcf().suptitle(t, **kwargs)
  568. @docstring.copy_dedent(Figure.figimage)
  569. def figimage(*args, **kwargs):
  570. return gcf().figimage(*args, **kwargs)
  571. def figlegend(*args, **kwargs):
  572. """
  573. Place a legend in the figure.
  574. *labels*
  575. a sequence of strings
  576. *handles*
  577. a sequence of :class:`~matplotlib.lines.Line2D` or
  578. :class:`~matplotlib.patches.Patch` instances
  579. *loc*
  580. can be a string or an integer specifying the legend
  581. location
  582. A :class:`matplotlib.legend.Legend` instance is returned.
  583. Examples
  584. --------
  585. To make a legend from existing artists on every axes::
  586. figlegend()
  587. To make a legend for a list of lines and labels::
  588. figlegend( (line1, line2, line3),
  589. ('label1', 'label2', 'label3'),
  590. 'upper right' )
  591. .. seealso::
  592. :func:`~matplotlib.pyplot.legend`
  593. """
  594. return gcf().legend(*args, **kwargs)
  595. ## Axes ##
  596. @docstring.dedent_interpd
  597. def axes(arg=None, **kwargs):
  598. """
  599. Add an axes to the current figure and make it the current axes.
  600. Call signatures::
  601. plt.axes()
  602. plt.axes(rect, projection=None, polar=False, **kwargs)
  603. plt.axes(ax)
  604. Parameters
  605. ----------
  606. arg : { None, 4-tuple, Axes }
  607. The exact behavior of this function depends on the type:
  608. - *None*: A new full window axes is added using
  609. ``subplot(111, **kwargs)``
  610. - 4-tuple of floats *rect* = ``[left, bottom, width, height]``.
  611. A new axes is added with dimensions *rect* in normalized
  612. (0, 1) units using `~.Figure.add_axes` on the current figure.
  613. - `~.axes.Axes`: This is equivalent to `.pyplot.sca`.
  614. It sets the current axes to *arg*. Note: This implicitly
  615. changes the current figure to the parent of *arg*.
  616. .. note:: The use of an `.axes.Axes` as an argument is deprecated
  617. and will be removed in v3.0. Please use `.pyplot.sca`
  618. instead.
  619. projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \
  620. 'polar', 'rectilinear', str}, optional
  621. The projection type of the `~.axes.Axes`. *str* is the name of
  622. a costum projection, see `~matplotlib.projections`. The default
  623. None results in a 'rectilinear' projection.
  624. polar : boolean, optional
  625. If True, equivalent to projection='polar'.
  626. sharex, sharey : `~.axes.Axes`, optional
  627. Share the x or y `~matplotlib.axis` with sharex and/or sharey.
  628. The axis will have the same limits, ticks, and scale as the axis
  629. of the shared axes.
  630. label : str
  631. A label for the returned axes.
  632. Other Parameters
  633. ----------------
  634. **kwargs
  635. This method also takes the keyword arguments for
  636. the returned axes class. The keyword arguments for the
  637. rectilinear axes class `~.axes.Axes` can be found in
  638. the following table but there might also be other keyword
  639. arguments if another projection is used, see the actual axes
  640. class.
  641. %(Axes)s
  642. Returns
  643. -------
  644. axes : `~.axes.Axes` (or a subclass of `~.axes.Axes`)
  645. The returned axes class depends on the projection used. It is
  646. `~.axes.Axes` if rectilinear projection are used and
  647. `.projections.polar.PolarAxes` if polar projection
  648. are used.
  649. Notes
  650. -----
  651. If the figure already has a axes with key (*args*,
  652. *kwargs*) then it will simply make that axes current and
  653. return it. This behavior is deprecated. Meanwhile, if you do
  654. not want this behavior (i.e., you want to force the creation of a
  655. new axes), you must use a unique set of args and kwargs. The axes
  656. *label* attribute has been exposed for this purpose: if you want
  657. two axes that are otherwise identical to be added to the figure,
  658. make sure you give them unique labels.
  659. See Also
  660. --------
  661. .Figure.add_axes
  662. .pyplot.subplot
  663. .Figure.add_subplot
  664. .Figure.subplots
  665. .pyplot.subplots
  666. Examples
  667. --------
  668. ::
  669. #Creating a new full window axes
  670. plt.axes()
  671. #Creating a new axes with specified dimensions and some kwargs
  672. plt.axes((left, bottom, width, height), facecolor='w')
  673. """
  674. if arg is None:
  675. return subplot(111, **kwargs)
  676. if isinstance(arg, Axes):
  677. warn_deprecated("2.2",
  678. message="Using pyplot.axes(ax) with ax an Axes "
  679. "argument is deprecated. Please use "
  680. "pyplot.sca(ax) instead.")
  681. ax = arg
  682. sca(ax)
  683. return ax
  684. else:
  685. rect = arg
  686. return gcf().add_axes(rect, **kwargs)
  687. def delaxes(ax=None):
  688. """
  689. Remove the `Axes` *ax* (defaulting to the current axes) from its figure.
  690. A KeyError is raised if the axes doesn't exist.
  691. """
  692. if ax is None:
  693. ax = gca()
  694. ax.figure.delaxes(ax)
  695. def sca(ax):
  696. """
  697. Set the current Axes instance to *ax*.
  698. The current Figure is updated to the parent of *ax*.
  699. """
  700. managers = _pylab_helpers.Gcf.get_all_fig_managers()
  701. for m in managers:
  702. if ax in m.canvas.figure.axes:
  703. _pylab_helpers.Gcf.set_active(m)
  704. m.canvas.figure.sca(ax)
  705. return
  706. raise ValueError("Axes instance argument was not found in a figure")
  707. def gca(**kwargs):
  708. """
  709. Get the current :class:`~matplotlib.axes.Axes` instance on the
  710. current figure matching the given keyword args, or create one.
  711. Examples
  712. --------
  713. To get the current polar axes on the current figure::
  714. plt.gca(projection='polar')
  715. If the current axes doesn't exist, or isn't a polar one, the appropriate
  716. axes will be created and then returned.
  717. See Also
  718. --------
  719. matplotlib.figure.Figure.gca : The figure's gca method.
  720. """
  721. return gcf().gca(**kwargs)
  722. ## More ways of creating axes ##
  723. @docstring.dedent_interpd
  724. def subplot(*args, **kwargs):
  725. """
  726. Add a subplot to the current figure.
  727. Wrapper of `.Figure.add_subplot` with a difference in behavior
  728. explained in the notes section.
  729. Call signatures::
  730. subplot(nrows, ncols, index, **kwargs)
  731. subplot(pos, **kwargs)
  732. subplot(ax)
  733. Parameters
  734. ----------
  735. *args
  736. Either a 3-digit integer or three separate integers
  737. describing the position of the subplot. If the three
  738. integers are *nrows*, *ncols*, and *index* in order, the
  739. subplot will take the *index* position on a grid with *nrows*
  740. rows and *ncols* columns. *index* starts at 1 in the upper left
  741. corner and increases to the right.
  742. *pos* is a three digit integer, where the first digit is the
  743. number of rows, the second the number of columns, and the third
  744. the index of the subplot. i.e. fig.add_subplot(235) is the same as
  745. fig.add_subplot(2, 3, 5). Note that all integers must be less than
  746. 10 for this form to work.
  747. projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \
  748. 'polar', 'rectilinear', str}, optional
  749. The projection type of the subplot (`~.axes.Axes`). *str* is the name
  750. of a costum projection, see `~matplotlib.projections`. The default
  751. None results in a 'rectilinear' projection.
  752. polar : boolean, optional
  753. If True, equivalent to projection='polar'.
  754. sharex, sharey : `~.axes.Axes`, optional
  755. Share the x or y `~matplotlib.axis` with sharex and/or sharey. The
  756. axis will have the same limits, ticks, and scale as the axis of the
  757. shared axes.
  758. label : str
  759. A label for the returned axes.
  760. Other Parameters
  761. ----------------
  762. **kwargs
  763. This method also takes the keyword arguments for
  764. the returned axes base class. The keyword arguments for the
  765. rectilinear base class `~.axes.Axes` can be found in
  766. the following table but there might also be other keyword
  767. arguments if another projection is used.
  768. %(Axes)s
  769. Returns
  770. -------
  771. axes : an `.axes.SubplotBase` subclass of `~.axes.Axes` (or a subclass \
  772. of `~.axes.Axes`)
  773. The axes of the subplot. The returned axes base class depends on
  774. the projection used. It is `~.axes.Axes` if rectilinear projection
  775. are used and `.projections.polar.PolarAxes` if polar projection
  776. are used. The returned axes is then a subplot subclass of the
  777. base class.
  778. Notes
  779. -----
  780. Creating a subplot will delete any pre-existing subplot that overlaps
  781. with it beyond sharing a boundary::
  782. import matplotlib.pyplot as plt
  783. # plot a line, implicitly creating a subplot(111)
  784. plt.plot([1,2,3])
  785. # now create a subplot which represents the top plot of a grid
  786. # with 2 rows and 1 column. Since this subplot will overlap the
  787. # first, the plot (and its axes) previously created, will be removed
  788. plt.subplot(211)
  789. If you do not want this behavior, use the `.Figure.add_subplot` method
  790. or the `.pyplot.axes` function instead.
  791. If the figure already has a subplot with key (*args*,
  792. *kwargs*) then it will simply make that subplot current and
  793. return it. This behavior is deprecated. Meanwhile, if you do
  794. not want this behavior (i.e., you want to force the creation of a
  795. new suplot), you must use a unique set of args and kwargs. The axes
  796. *label* attribute has been exposed for this purpose: if you want
  797. two subplots that are otherwise identical to be added to the figure,
  798. make sure you give them unique labels.
  799. In rare circumstances, `.add_subplot` may be called with a single
  800. argument, a subplot axes instance already created in the
  801. present figure but not in the figure's list of axes.
  802. See Also
  803. --------
  804. .Figure.add_subplot
  805. .pyplot.subplots
  806. .pyplot.axes
  807. .Figure.subplots
  808. Examples
  809. --------
  810. ::
  811. plt.subplot(221)
  812. # equivalent but more general
  813. ax1=plt.subplot(2, 2, 1)
  814. # add a subplot with no frame
  815. ax2=plt.subplot(222, frameon=False)
  816. # add a polar subplot
  817. plt.subplot(223, projection='polar')
  818. # add a red subplot that shares the x-axis with ax1
  819. plt.subplot(224, sharex=ax1, facecolor='red')
  820. #delete ax2 from the figure
  821. plt.delaxes(ax2)
  822. #add ax2 to the figure again
  823. plt.subplot(ax2)
  824. """
  825. # if subplot called without arguments, create subplot(1,1,1)
  826. if len(args) == 0:
  827. args = (1, 1, 1)
  828. # This check was added because it is very easy to type
  829. # subplot(1, 2, False) when subplots(1, 2, False) was intended
  830. # (sharex=False, that is). In most cases, no error will
  831. # ever occur, but mysterious behavior can result because what was
  832. # intended to be the sharex argument is instead treated as a
  833. # subplot index for subplot()
  834. if len(args) >= 3 and isinstance(args[2], bool):
  835. warnings.warn("The subplot index argument to subplot() appears "
  836. "to be a boolean. Did you intend to use subplots()?")
  837. fig = gcf()
  838. a = fig.add_subplot(*args, **kwargs)
  839. bbox = a.bbox
  840. byebye = []
  841. for other in fig.axes:
  842. if other == a:
  843. continue
  844. if bbox.fully_overlaps(other.bbox):
  845. byebye.append(other)
  846. for ax in byebye:
  847. delaxes(ax)
  848. return a
  849. def subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True,
  850. subplot_kw=None, gridspec_kw=None, **fig_kw):
  851. """
  852. Create a figure and a set of subplots.
  853. This utility wrapper makes it convenient to create common layouts of
  854. subplots, including the enclosing figure object, in a single call.
  855. Parameters
  856. ----------
  857. nrows, ncols : int, optional, default: 1
  858. Number of rows/columns of the subplot grid.
  859. sharex, sharey : bool or {'none', 'all', 'row', 'col'}, default: False
  860. Controls sharing of properties among x (`sharex`) or y (`sharey`)
  861. axes:
  862. - True or 'all': x- or y-axis will be shared among all
  863. subplots.
  864. - False or 'none': each subplot x- or y-axis will be
  865. independent.
  866. - 'row': each subplot row will share an x- or y-axis.
  867. - 'col': each subplot column will share an x- or y-axis.
  868. When subplots have a shared x-axis along a column, only the x tick
  869. labels of the bottom subplot are created. Similarly, when subplots
  870. have a shared y-axis along a row, only the y tick labels of the first
  871. column subplot are created. To later turn other subplots' ticklabels
  872. on, use `~matplotlib.axes.Axes.tick_params`.
  873. squeeze : bool, optional, default: True
  874. - If True, extra dimensions are squeezed out from the returned
  875. array of `~matplotlib.axes.Axes`:
  876. - if only one subplot is constructed (nrows=ncols=1), the
  877. resulting single Axes object is returned as a scalar.
  878. - for Nx1 or 1xM subplots, the returned object is a 1D numpy
  879. object array of Axes objects.
  880. - for NxM, subplots with N>1 and M>1 are returned as a 2D array.
  881. - If False, no squeezing at all is done: the returned Axes object is
  882. always a 2D array containing Axes instances, even if it ends up
  883. being 1x1.
  884. num : integer or string, optional, default: None
  885. A `.pyplot.figure` keyword that sets the figure number or label.
  886. subplot_kw : dict, optional
  887. Dict with keywords passed to the
  888. `~matplotlib.figure.Figure.add_subplot` call used to create each
  889. subplot.
  890. gridspec_kw : dict, optional
  891. Dict with keywords passed to the `~matplotlib.gridspec.GridSpec`
  892. constructor used to create the grid the subplots are placed on.
  893. **fig_kw :
  894. All additional keyword arguments are passed to the
  895. `.pyplot.figure` call.
  896. Returns
  897. -------
  898. fig : `~.figure.Figure`
  899. ax : `.axes.Axes` object or array of Axes objects.
  900. *ax* can be either a single `~matplotlib.axes.Axes` object or an
  901. array of Axes objects if more than one subplot was created. The
  902. dimensions of the resulting array can be controlled with the squeeze
  903. keyword, see above.
  904. Examples
  905. --------
  906. ::
  907. #First create some toy data:
  908. x = np.linspace(0, 2*np.pi, 400)
  909. y = np.sin(x**2)
  910. #Creates just a figure and only one subplot
  911. fig, ax = plt.subplots()
  912. ax.plot(x, y)
  913. ax.set_title('Simple plot')
  914. #Creates two subplots and unpacks the output array immediately
  915. f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
  916. ax1.plot(x, y)
  917. ax1.set_title('Sharing Y axis')
  918. ax2.scatter(x, y)
  919. #Creates four polar axes, and accesses them through the returned array
  920. fig, axes = plt.subplots(2, 2, subplot_kw=dict(polar=True))
  921. axes[0, 0].plot(x, y)
  922. axes[1, 1].scatter(x, y)
  923. #Share a X axis with each column of subplots
  924. plt.subplots(2, 2, sharex='col')
  925. #Share a Y axis with each row of subplots
  926. plt.subplots(2, 2, sharey='row')
  927. #Share both X and Y axes with all subplots
  928. plt.subplots(2, 2, sharex='all', sharey='all')
  929. #Note that this is the same as
  930. plt.subplots(2, 2, sharex=True, sharey=True)
  931. #Creates figure number 10 with a single subplot
  932. #and clears it if it already exists.
  933. fig, ax=plt.subplots(num=10, clear=True)
  934. See Also
  935. --------
  936. .pyplot.figure
  937. .pyplot.subplot
  938. .pyplot.axes
  939. .Figure.subplots
  940. .Figure.add_subplot
  941. """
  942. fig = figure(**fig_kw)
  943. axs = fig.subplots(nrows=nrows, ncols=ncols, sharex=sharex, sharey=sharey,
  944. squeeze=squeeze, subplot_kw=subplot_kw,
  945. gridspec_kw=gridspec_kw)
  946. return fig, axs
  947. def subplot2grid(shape, loc, rowspan=1, colspan=1, fig=None, **kwargs):
  948. """
  949. Create an axis at specific location inside a regular grid.
  950. Parameters
  951. ----------
  952. shape : sequence of 2 ints
  953. Shape of grid in which to place axis.
  954. First entry is number of rows, second entry is number of columns.
  955. loc : sequence of 2 ints
  956. Location to place axis within grid.
  957. First entry is row number, second entry is column number.
  958. rowspan : int
  959. Number of rows for the axis to span to the right.
  960. colspan : int
  961. Number of columns for the axis to span downwards.
  962. fig : `Figure`, optional
  963. Figure to place axis in. Defaults to current figure.
  964. **kwargs
  965. Additional keyword arguments are handed to `add_subplot`.
  966. Notes
  967. -----
  968. The following call ::
  969. subplot2grid(shape, loc, rowspan=1, colspan=1)
  970. is identical to ::
  971. gridspec=GridSpec(shape[0], shape[1])
  972. subplotspec=gridspec.new_subplotspec(loc, rowspan, colspan)
  973. subplot(subplotspec)
  974. """
  975. if fig is None:
  976. fig = gcf()
  977. s1, s2 = shape
  978. subplotspec = GridSpec(s1, s2).new_subplotspec(loc,
  979. rowspan=rowspan,
  980. colspan=colspan)
  981. a = fig.add_subplot(subplotspec, **kwargs)
  982. bbox = a.bbox
  983. byebye = []
  984. for other in fig.axes:
  985. if other == a:
  986. continue
  987. if bbox.fully_overlaps(other.bbox):
  988. byebye.append(other)
  989. for ax in byebye:
  990. delaxes(ax)
  991. return a
  992. def twinx(ax=None):
  993. """
  994. Make a second axes that shares the *x*-axis. The new axes will
  995. overlay *ax* (or the current axes if *ax* is *None*). The ticks
  996. for *ax2* will be placed on the right, and the *ax2* instance is
  997. returned.
  998. .. seealso::
  999. :doc:`/gallery/subplots_axes_and_figures/two_scales`
  1000. """
  1001. if ax is None:
  1002. ax = gca()
  1003. ax1 = ax.twinx()
  1004. return ax1
  1005. def twiny(ax=None):
  1006. """
  1007. Make a second axes that shares the *y*-axis. The new axis will
  1008. overlay *ax* (or the current axes if *ax* is *None*). The ticks
  1009. for *ax2* will be placed on the top, and the *ax2* instance is
  1010. returned.
  1011. """
  1012. if ax is None:
  1013. ax = gca()
  1014. ax1 = ax.twiny()
  1015. return ax1
  1016. def subplots_adjust(left=None, bottom=None, right=None, top=None,
  1017. wspace=None, hspace=None):
  1018. """
  1019. Tune the subplot layout.
  1020. The parameter meanings (and suggested defaults) are::
  1021. left = 0.125 # the left side of the subplots of the figure
  1022. right = 0.9 # the right side of the subplots of the figure
  1023. bottom = 0.1 # the bottom of the subplots of the figure
  1024. top = 0.9 # the top of the subplots of the figure
  1025. wspace = 0.2 # the amount of width reserved for space between subplots,
  1026. # expressed as a fraction of the average axis width
  1027. hspace = 0.2 # the amount of height reserved for space between subplots,
  1028. # expressed as a fraction of the average axis height
  1029. The actual defaults are controlled by the rc file
  1030. """
  1031. fig = gcf()
  1032. fig.subplots_adjust(left, bottom, right, top, wspace, hspace)
  1033. def subplot_tool(targetfig=None):
  1034. """
  1035. Launch a subplot tool window for a figure.
  1036. A :class:`matplotlib.widgets.SubplotTool` instance is returned.
  1037. """
  1038. tbar = rcParams['toolbar'] # turn off the navigation toolbar for the toolfig
  1039. rcParams['toolbar'] = 'None'
  1040. if targetfig is None:
  1041. manager = get_current_fig_manager()
  1042. targetfig = manager.canvas.figure
  1043. else:
  1044. # find the manager for this figure
  1045. for manager in _pylab_helpers.Gcf._activeQue:
  1046. if manager.canvas.figure == targetfig:
  1047. break
  1048. else:
  1049. raise RuntimeError('Could not find manager for targetfig')
  1050. toolfig = figure(figsize=(6,3))
  1051. toolfig.subplots_adjust(top=0.9)
  1052. ret = SubplotTool(targetfig, toolfig)
  1053. rcParams['toolbar'] = tbar
  1054. _pylab_helpers.Gcf.set_active(manager) # restore the current figure
  1055. return ret
  1056. def tight_layout(pad=1.08, h_pad=None, w_pad=None, rect=None):
  1057. """
  1058. Automatically adjust subplot parameters to give specified padding.
  1059. Parameters
  1060. ----------
  1061. pad : float
  1062. Padding between the figure edge and the edges of subplots,
  1063. as a fraction of the font size.
  1064. h_pad, w_pad : float, optional
  1065. Padding (height/width) between edges of adjacent subplots,
  1066. as a fraction of the font size. Defaults to *pad*.
  1067. rect : tuple (left, bottom, right, top), optional
  1068. A rectangle (left, bottom, right, top) in the normalized
  1069. figure coordinate that the whole subplots area (including
  1070. labels) will fit into. Default is (0, 0, 1, 1).
  1071. """
  1072. gcf().tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
  1073. def box(on=None):
  1074. """
  1075. Turn the axes box on or off on the current axes.
  1076. Parameters
  1077. ----------
  1078. on : bool or None
  1079. The new `~matplotlib.axes.Axes` box state. If ``None``, toggle
  1080. the state.
  1081. See Also
  1082. --------
  1083. :meth:`matplotlib.axes.Axes.set_frame_on`
  1084. :meth:`matplotlib.axes.Axes.get_frame_on`
  1085. """
  1086. ax = gca()
  1087. if on is None:
  1088. on = not ax.get_frame_on()
  1089. on = _string_to_bool(on)
  1090. ax.set_frame_on(on)
  1091. ## Axis ##
  1092. def xlim(*args, **kwargs):
  1093. """
  1094. Get or set the x limits of the current axes.
  1095. Call signatures::
  1096. left, right = xlim() # return the current xlim
  1097. xlim((left, right)) # set the xlim to left, right
  1098. xlim(left, right) # set the xlim to left, right
  1099. If you do not specify args, you can pass *left* or *right* as kwargs,
  1100. i.e.::
  1101. xlim(right=3) # adjust the right leaving left unchanged
  1102. xlim(left=1) # adjust the left leaving right unchanged
  1103. Setting limits turns autoscaling off for the x-axis.
  1104. Returns
  1105. -------
  1106. left, right
  1107. A tuple of the new x-axis limits.
  1108. Notes
  1109. -----
  1110. Calling this function with no arguments (e.g. ``xlim()``) is the pyplot
  1111. equivalent of calling `~.Axes.get_xlim` on the current axes.
  1112. Calling this function with arguments is the pyplot equivalent of calling
  1113. `~.Axes.set_xlim` on the current axes. All arguments are passed though.
  1114. """
  1115. ax = gca()
  1116. if not args and not kwargs:
  1117. return ax.get_xlim()
  1118. ret = ax.set_xlim(*args, **kwargs)
  1119. return ret
  1120. def ylim(*args, **kwargs):
  1121. """
  1122. Get or set the y-limits of the current axes.
  1123. Call signatures::
  1124. bottom, top = ylim() # return the current ylim
  1125. ylim((bottom, top)) # set the ylim to bottom, top
  1126. ylim(bottom, top) # set the ylim to bottom, top
  1127. If you do not specify args, you can alternatively pass *bottom* or
  1128. *top* as kwargs, i.e.::
  1129. ylim(top=3) # adjust the top leaving bottom unchanged
  1130. ylim(bottom=1) # adjust the bottom leaving top unchanged
  1131. Setting limits turns autoscaling off for the y-axis.
  1132. Returns
  1133. -------
  1134. bottom, top
  1135. A tuple of the new y-axis limits.
  1136. Notes
  1137. -----
  1138. Calling this function with no arguments (e.g. ``ylim()``) is the pyplot
  1139. equivalent of calling `~.Axes.get_ylim` on the current axes.
  1140. Calling this function with arguments is the pyplot equivalent of calling
  1141. `~.Axes.set_ylim` on the current axes. All arguments are passed though.
  1142. """
  1143. ax = gca()
  1144. if not args and not kwargs:
  1145. return ax.get_ylim()
  1146. ret = ax.set_ylim(*args, **kwargs)
  1147. return ret
  1148. def xticks(ticks=None, labels=None, **kwargs):
  1149. """
  1150. Get or set the current tick locations and labels of the x-axis.
  1151. Call signatures::
  1152. locs, labels = xticks() # Get locations and labels
  1153. xticks(ticks, [labels], **kwargs) # Set locations and labels
  1154. Parameters
  1155. ----------
  1156. ticks : array_like
  1157. A list of positions at which ticks should be placed. You can pass an
  1158. empty list to disable xticks.
  1159. labels : array_like, optional
  1160. A list of explicit labels to place at the given *locs*.
  1161. **kwargs
  1162. :class:`.Text` properties can be used to control the appearance of
  1163. the labels.
  1164. Returns
  1165. -------
  1166. locs
  1167. An array of label locations.
  1168. labels
  1169. A list of `.Text` objects.
  1170. Notes
  1171. -----
  1172. Calling this function with no arguments (e.g. ``xticks()``) is the pyplot
  1173. equivalent of calling `~.Axes.get_xticks` and `~.Axes.get_xticklabels` on
  1174. the current axes.
  1175. Calling this function with arguments is the pyplot equivalent of calling
  1176. `~.Axes.set_xticks` and `~.Axes.set_xticklabels` on the current axes.
  1177. Examples
  1178. --------
  1179. Get the current locations and labels:
  1180. >>> locs, labels = xticks()
  1181. Set label locations:
  1182. >>> xticks(np.arange(0, 1, step=0.2))
  1183. Set text labels:
  1184. >>> xticks(np.arange(5), ('Tom', 'Dick', 'Harry', 'Sally', 'Sue'))
  1185. Set text labels and properties:
  1186. >>> xticks(np.arange(12), calendar.month_name[1:13], rotation=20)
  1187. Disable xticks:
  1188. >>> xticks([])
  1189. """
  1190. ax = gca()
  1191. if ticks is None and labels is None:
  1192. locs = ax.get_xticks()
  1193. labels = ax.get_xticklabels()
  1194. elif labels is None:
  1195. locs = ax.set_xticks(ticks)
  1196. labels = ax.get_xticklabels()
  1197. else:
  1198. locs = ax.set_xticks(ticks)
  1199. labels = ax.set_xticklabels(labels, **kwargs)
  1200. for l in labels:
  1201. l.update(kwargs)
  1202. return locs, silent_list('Text xticklabel', labels)
  1203. def yticks(ticks=None, labels=None, **kwargs):
  1204. """
  1205. Get or set the current tick locations and labels of the y-axis.
  1206. Call signatures::
  1207. locs, labels = yticks() # Get locations and labels
  1208. yticks(ticks, [labels], **kwargs) # Set locations and labels
  1209. Parameters
  1210. ----------
  1211. ticks : array_like
  1212. A list of positions at which ticks should be placed. You can pass an
  1213. empty list to disable yticks.
  1214. labels : array_like, optional
  1215. A list of explicit labels to place at the given *locs*.
  1216. **kwargs
  1217. :class:`.Text` properties can be used to control the appearance of
  1218. the labels.
  1219. Returns
  1220. -------
  1221. locs
  1222. An array of label locations.
  1223. labels
  1224. A list of `.Text` objects.
  1225. Notes
  1226. -----
  1227. Calling this function with no arguments (e.g. ``yticks()``) is the pyplot
  1228. equivalent of calling `~.Axes.get_yticks` and `~.Axes.get_yticklabels` on
  1229. the current axes.
  1230. Calling this function with arguments is the pyplot equivalent of calling
  1231. `~.Axes.set_yticks` and `~.Axes.set_yticklabels` on the current axes.
  1232. Examples
  1233. --------
  1234. Get the current locations and labels:
  1235. >>> locs, labels = yticks()
  1236. Set label locations:
  1237. >>> yticks(np.arange(0, 1, step=0.2))
  1238. Set text labels:
  1239. >>> yticks(np.arange(5), ('Tom', 'Dick', 'Harry', 'Sally', 'Sue'))
  1240. Set text labels and properties:
  1241. >>> yticks(np.arange(12), calendar.month_name[1:13], rotation=45)
  1242. Disable yticks:
  1243. >>> yticks([])
  1244. """
  1245. ax = gca()
  1246. if ticks is None and labels is None:
  1247. locs = ax.get_yticks()
  1248. labels = ax.get_yticklabels()
  1249. elif labels is None:
  1250. locs = ax.set_yticks(ticks)
  1251. labels = ax.get_yticklabels()
  1252. else:
  1253. locs = ax.set_yticks(ticks)
  1254. labels = ax.set_yticklabels(labels, **kwargs)
  1255. for l in labels:
  1256. l.update(kwargs)
  1257. return locs, silent_list('Text yticklabel', labels)
  1258. def rgrids(*args, **kwargs):
  1259. """
  1260. Get or set the radial gridlines on the current polar plot.
  1261. Call signatures::
  1262. lines, labels = rgrids()
  1263. lines, labels = rgrids(radii, labels=None, angle=22.5, fmt=None, **kwargs)
  1264. When called with no arguments, `.rgrids` simply returns the tuple
  1265. (*lines*, *labels*). When called with arguments, the labels will
  1266. appear at the specified radial distances and angle.
  1267. Parameters
  1268. ----------
  1269. radii : tuple with floats
  1270. The radii for the radial gridlines
  1271. labels : tuple with strings or None
  1272. The labels to use at each radial gridline. The
  1273. `matplotlib.ticker.ScalarFormatter` will be used if None.
  1274. angle : float
  1275. The angular position of the radius labels in degrees.
  1276. fmt : str or None
  1277. Format string used in `matplotlib.ticker.FormatStrFormatter`.
  1278. For example '%f'.
  1279. Returns
  1280. -------
  1281. lines, labels : list of `.lines.Line2D`, list of `.text.Text`
  1282. *lines* are the radial gridlines and *labels* are the tick labels.
  1283. Other Parameters
  1284. ----------------
  1285. **kwargs
  1286. *kwargs* are optional `~.Text` properties for the labels.
  1287. Examples
  1288. --------
  1289. ::
  1290. # set the locations of the radial gridlines
  1291. lines, labels = rgrids( (0.25, 0.5, 1.0) )
  1292. # set the locations and labels of the radial gridlines
  1293. lines, labels = rgrids( (0.25, 0.5, 1.0), ('Tom', 'Dick', 'Harry' ))
  1294. See Also
  1295. --------
  1296. .pyplot.thetagrids
  1297. .projections.polar.PolarAxes.set_rgrids
  1298. .Axis.get_gridlines
  1299. .Axis.get_ticklabels
  1300. """
  1301. ax = gca()
  1302. if not isinstance(ax, PolarAxes):
  1303. raise RuntimeError('rgrids only defined for polar axes')
  1304. if len(args)==0:
  1305. lines = ax.yaxis.get_gridlines()
  1306. labels = ax.yaxis.get_ticklabels()
  1307. else:
  1308. lines, labels = ax.set_rgrids(*args, **kwargs)
  1309. return ( silent_list('Line2D rgridline', lines),
  1310. silent_list('Text rgridlabel', labels) )
  1311. def thetagrids(*args, **kwargs):
  1312. """
  1313. Get or set the theta gridlines on the current polar plot.
  1314. Call signatures::
  1315. lines, labels = thetagrids()
  1316. lines, labels = thetagrids(angles, labels=None, fmt=None, **kwargs)
  1317. When called with no arguments, `.thetagrids` simply returns the tuple
  1318. (*lines*, *labels*). When called with arguments, the labels will
  1319. appear at the specified angles.
  1320. Parameters
  1321. ----------
  1322. angles : tuple with floats, degrees
  1323. The angles of the theta gridlines.
  1324. labels : tuple with strings or None
  1325. The labels to use at each radial gridline. The
  1326. `.projections.polar.ThetaFormatter` will be used if None.
  1327. fmt : str or None
  1328. Format string used in `matplotlib.ticker.FormatStrFormatter`.
  1329. For example '%f'. Note that the angle in radians will be used.
  1330. Returns
  1331. -------
  1332. lines, labels : list of `.lines.Line2D`, list of `.text.Text`
  1333. *lines* are the theta gridlines and *labels* are the tick labels.
  1334. Other Parameters
  1335. ----------------
  1336. **kwargs
  1337. *kwargs* are optional `~.Text` properties for the labels.
  1338. Examples
  1339. --------
  1340. ::
  1341. # set the locations of the angular gridlines
  1342. lines, labels = thetagrids( range(45,360,90) )
  1343. # set the locations and labels of the angular gridlines
  1344. lines, labels = thetagrids( range(45,360,90), ('NE', 'NW', 'SW','SE') )
  1345. See Also
  1346. --------
  1347. .pyplot.rgrids
  1348. .projections.polar.PolarAxes.set_thetagrids
  1349. .Axis.get_gridlines
  1350. .Axis.get_ticklabels
  1351. """
  1352. ax = gca()
  1353. if not isinstance(ax, PolarAxes):
  1354. raise RuntimeError('thetagrids only defined for polar axes')
  1355. if len(args)==0:
  1356. lines = ax.xaxis.get_ticklines()
  1357. labels = ax.xaxis.get_ticklabels()
  1358. else:
  1359. lines, labels = ax.set_thetagrids(*args, **kwargs)
  1360. return (silent_list('Line2D thetagridline', lines),
  1361. silent_list('Text thetagridlabel', labels)
  1362. )
  1363. ## Plotting Info ##
  1364. def plotting():
  1365. pass
  1366. def get_plot_commands():
  1367. """
  1368. Get a sorted list of all of the plotting commands.
  1369. """
  1370. # This works by searching for all functions in this module and removing
  1371. # a few hard-coded exclusions, as well as all of the colormap-setting
  1372. # functions, and anything marked as private with a preceding underscore.
  1373. exclude = {'colormaps', 'colors', 'connect', 'disconnect',
  1374. 'get_plot_commands', 'get_current_fig_manager', 'ginput',
  1375. 'plotting', 'waitforbuttonpress'}
  1376. exclude |= set(colormaps())
  1377. this_module = inspect.getmodule(get_plot_commands)
  1378. return sorted(
  1379. name for name, obj in globals().items()
  1380. if not name.startswith('_') and name not in exclude
  1381. and inspect.isfunction(obj)
  1382. and inspect.getmodule(obj) is this_module)
  1383. def colormaps():
  1384. """
  1385. Matplotlib provides a number of colormaps, and others can be added using
  1386. :func:`~matplotlib.cm.register_cmap`. This function documents the built-in
  1387. colormaps, and will also return a list of all registered colormaps if called.
  1388. You can set the colormap for an image, pcolor, scatter, etc,
  1389. using a keyword argument::
  1390. imshow(X, cmap=cm.hot)
  1391. or using the :func:`set_cmap` function::
  1392. imshow(X)
  1393. pyplot.set_cmap('hot')
  1394. pyplot.set_cmap('jet')
  1395. In interactive mode, :func:`set_cmap` will update the colormap post-hoc,
  1396. allowing you to see which one works best for your data.
  1397. All built-in colormaps can be reversed by appending ``_r``: For instance,
  1398. ``gray_r`` is the reverse of ``gray``.
  1399. There are several common color schemes used in visualization:
  1400. Sequential schemes
  1401. for unipolar data that progresses from low to high
  1402. Diverging schemes
  1403. for bipolar data that emphasizes positive or negative deviations from a
  1404. central value
  1405. Cyclic schemes
  1406. for plotting values that wrap around at the endpoints, such as phase
  1407. angle, wind direction, or time of day
  1408. Qualitative schemes
  1409. for nominal data that has no inherent ordering, where color is used
  1410. only to distinguish categories
  1411. Matplotlib ships with 4 perceptually uniform color maps which are
  1412. the recommended color maps for sequential data:
  1413. ========= ===================================================
  1414. Colormap Description
  1415. ========= ===================================================
  1416. inferno perceptually uniform shades of black-red-yellow
  1417. magma perceptually uniform shades of black-red-white
  1418. plasma perceptually uniform shades of blue-red-yellow
  1419. viridis perceptually uniform shades of blue-green-yellow
  1420. ========= ===================================================
  1421. The following colormaps are based on the `ColorBrewer
  1422. <http://colorbrewer2.org>`_ color specifications and designs developed by
  1423. Cynthia Brewer:
  1424. ColorBrewer Diverging (luminance is highest at the midpoint, and
  1425. decreases towards differently-colored endpoints):
  1426. ======== ===================================
  1427. Colormap Description
  1428. ======== ===================================
  1429. BrBG brown, white, blue-green
  1430. PiYG pink, white, yellow-green
  1431. PRGn purple, white, green
  1432. PuOr orange, white, purple
  1433. RdBu red, white, blue
  1434. RdGy red, white, gray
  1435. RdYlBu red, yellow, blue
  1436. RdYlGn red, yellow, green
  1437. Spectral red, orange, yellow, green, blue
  1438. ======== ===================================
  1439. ColorBrewer Sequential (luminance decreases monotonically):
  1440. ======== ====================================
  1441. Colormap Description
  1442. ======== ====================================
  1443. Blues white to dark blue
  1444. BuGn white, light blue, dark green
  1445. BuPu white, light blue, dark purple
  1446. GnBu white, light green, dark blue
  1447. Greens white to dark green
  1448. Greys white to black (not linear)
  1449. Oranges white, orange, dark brown
  1450. OrRd white, orange, dark red
  1451. PuBu white, light purple, dark blue
  1452. PuBuGn white, light purple, dark green
  1453. PuRd white, light purple, dark red
  1454. Purples white to dark purple
  1455. RdPu white, pink, dark purple
  1456. Reds white to dark red
  1457. YlGn light yellow, dark green
  1458. YlGnBu light yellow, light green, dark blue
  1459. YlOrBr light yellow, orange, dark brown
  1460. YlOrRd light yellow, orange, dark red
  1461. ======== ====================================
  1462. ColorBrewer Qualitative:
  1463. (For plotting nominal data, :class:`ListedColormap` is used,
  1464. not :class:`LinearSegmentedColormap`. Different sets of colors are
  1465. recommended for different numbers of categories.)
  1466. * Accent
  1467. * Dark2
  1468. * Paired
  1469. * Pastel1
  1470. * Pastel2
  1471. * Set1
  1472. * Set2
  1473. * Set3
  1474. A set of colormaps derived from those of the same name provided
  1475. with Matlab are also included:
  1476. ========= =======================================================
  1477. Colormap Description
  1478. ========= =======================================================
  1479. autumn sequential linearly-increasing shades of red-orange-yellow
  1480. bone sequential increasing black-white color map with
  1481. a tinge of blue, to emulate X-ray film
  1482. cool linearly-decreasing shades of cyan-magenta
  1483. copper sequential increasing shades of black-copper
  1484. flag repetitive red-white-blue-black pattern (not cyclic at
  1485. endpoints)
  1486. gray sequential linearly-increasing black-to-white
  1487. grayscale
  1488. hot sequential black-red-yellow-white, to emulate blackbody
  1489. radiation from an object at increasing temperatures
  1490. jet a spectral map with dark endpoints, blue-cyan-yellow-red;
  1491. based on a fluid-jet simulation by NCSA [#]_
  1492. pink sequential increasing pastel black-pink-white, meant
  1493. for sepia tone colorization of photographs
  1494. prism repetitive red-yellow-green-blue-purple-...-green pattern
  1495. (not cyclic at endpoints)
  1496. spring linearly-increasing shades of magenta-yellow
  1497. summer sequential linearly-increasing shades of green-yellow
  1498. winter linearly-increasing shades of blue-green
  1499. ========= =======================================================
  1500. A set of palettes from the `Yorick scientific visualisation
  1501. package <https://dhmunro.github.io/yorick-doc/>`_, an evolution of
  1502. the GIST package, both by David H. Munro are included:
  1503. ============ =======================================================
  1504. Colormap Description
  1505. ============ =======================================================
  1506. gist_earth mapmaker's colors from dark blue deep ocean to green
  1507. lowlands to brown highlands to white mountains
  1508. gist_heat sequential increasing black-red-orange-white, to emulate
  1509. blackbody radiation from an iron bar as it grows hotter
  1510. gist_ncar pseudo-spectral black-blue-green-yellow-red-purple-white
  1511. colormap from National Center for Atmospheric
  1512. Research [#]_
  1513. gist_rainbow runs through the colors in spectral order from red to
  1514. violet at full saturation (like *hsv* but not cyclic)
  1515. gist_stern "Stern special" color table from Interactive Data
  1516. Language software
  1517. ============ =======================================================
  1518. A set of cyclic color maps:
  1519. ================ =========================================================
  1520. Colormap Description
  1521. ================ =========================================================
  1522. hsv red-yellow-green-cyan-blue-magenta-red, formed by changing
  1523. the hue component in the HSV color space
  1524. twilight perceptually uniform shades of white-blue-black-red-white
  1525. twilight_shifted perceptually uniform shades of black-blue-white-red-black
  1526. ================ =========================================================
  1527. Other miscellaneous schemes:
  1528. ============= =======================================================
  1529. Colormap Description
  1530. ============= =======================================================
  1531. afmhot sequential black-orange-yellow-white blackbody
  1532. spectrum, commonly used in atomic force microscopy
  1533. brg blue-red-green
  1534. bwr diverging blue-white-red
  1535. coolwarm diverging blue-gray-red, meant to avoid issues with 3D
  1536. shading, color blindness, and ordering of colors [#]_
  1537. CMRmap "Default colormaps on color images often reproduce to
  1538. confusing grayscale images. The proposed colormap
  1539. maintains an aesthetically pleasing color image that
  1540. automatically reproduces to a monotonic grayscale with
  1541. discrete, quantifiable saturation levels." [#]_
  1542. cubehelix Unlike most other color schemes cubehelix was designed
  1543. by D.A. Green to be monotonically increasing in terms
  1544. of perceived brightness. Also, when printed on a black
  1545. and white postscript printer, the scheme results in a
  1546. greyscale with monotonically increasing brightness.
  1547. This color scheme is named cubehelix because the r,g,b
  1548. values produced can be visualised as a squashed helix
  1549. around the diagonal in the r,g,b color cube.
  1550. gnuplot gnuplot's traditional pm3d scheme
  1551. (black-blue-red-yellow)
  1552. gnuplot2 sequential color printable as gray
  1553. (black-blue-violet-yellow-white)
  1554. ocean green-blue-white
  1555. rainbow spectral purple-blue-green-yellow-orange-red colormap
  1556. with diverging luminance
  1557. seismic diverging blue-white-red
  1558. nipy_spectral black-purple-blue-green-yellow-red-white spectrum,
  1559. originally from the Neuroimaging in Python project
  1560. terrain mapmaker's colors, blue-green-yellow-brown-white,
  1561. originally from IGOR Pro
  1562. ============= =======================================================
  1563. The following colormaps are redundant and may be removed in future
  1564. versions. It's recommended to use the names in the descriptions
  1565. instead, which produce identical output:
  1566. ========= =======================================================
  1567. Colormap Description
  1568. ========= =======================================================
  1569. gist_gray identical to *gray*
  1570. gist_yarg identical to *gray_r*
  1571. binary identical to *gray_r*
  1572. ========= =======================================================
  1573. .. rubric:: Footnotes
  1574. .. [#] Rainbow colormaps, ``jet`` in particular, are considered a poor
  1575. choice for scientific visualization by many researchers: `Rainbow Color
  1576. Map (Still) Considered Harmful
  1577. <http://ieeexplore.ieee.org/document/4118486/?arnumber=4118486>`_
  1578. .. [#] Resembles "BkBlAqGrYeOrReViWh200" from NCAR Command
  1579. Language. See `Color Table Gallery
  1580. <https://www.ncl.ucar.edu/Document/Graphics/color_table_gallery.shtml>`_
  1581. .. [#] See `Diverging Color Maps for Scientific Visualization
  1582. <http://www.kennethmoreland.com/color-maps/>`_ by Kenneth Moreland.
  1583. .. [#] See `A Color Map for Effective Black-and-White Rendering of
  1584. Color-Scale Images
  1585. <https://www.mathworks.com/matlabcentral/fileexchange/2662-cmrmap-m>`_
  1586. by Carey Rappaport
  1587. """
  1588. return sorted(cm.cmap_d)
  1589. def _setup_pyplot_info_docstrings():
  1590. """
  1591. Generates the plotting docstring.
  1592. These must be done after the entire module is imported, so it is
  1593. called from the end of this module, which is generated by
  1594. boilerplate.py.
  1595. """
  1596. commands = get_plot_commands()
  1597. first_sentence = re.compile(r"(?:\s*).+?\.(?:\s+|$)", flags=re.DOTALL)
  1598. # Collect the first sentence of the docstring for all of the
  1599. # plotting commands.
  1600. rows = []
  1601. max_name = len("Function")
  1602. max_summary = len("Description")
  1603. for name in commands:
  1604. doc = globals()[name].__doc__
  1605. summary = ''
  1606. if doc is not None:
  1607. match = first_sentence.match(doc)
  1608. if match is not None:
  1609. summary = inspect.cleandoc(match.group(0)).replace('\n', ' ')
  1610. name = '`%s`' % name
  1611. rows.append([name, summary])
  1612. max_name = max(max_name, len(name))
  1613. max_summary = max(max_summary, len(summary))
  1614. separator = '=' * max_name + ' ' + '=' * max_summary
  1615. lines = [
  1616. separator,
  1617. '{:{}} {:{}}'.format('Function', max_name, 'Description', max_summary),
  1618. separator,
  1619. ] + [
  1620. '{:{}} {:{}}'.format(name, max_name, summary, max_summary)
  1621. for name, summary in rows
  1622. ] + [
  1623. separator,
  1624. ]
  1625. plotting.__doc__ = '\n'.join(lines)
  1626. ## Plotting part 1: manually generated functions and wrappers ##
  1627. def colorbar(mappable=None, cax=None, ax=None, **kw):
  1628. if mappable is None:
  1629. mappable = gci()
  1630. if mappable is None:
  1631. raise RuntimeError('No mappable was found to use for colorbar '
  1632. 'creation. First define a mappable such as '
  1633. 'an image (with imshow) or a contour set ('
  1634. 'with contourf).')
  1635. if ax is None:
  1636. ax = gca()
  1637. ret = gcf().colorbar(mappable, cax = cax, ax=ax, **kw)
  1638. return ret
  1639. colorbar.__doc__ = matplotlib.colorbar.colorbar_doc
  1640. def clim(vmin=None, vmax=None):
  1641. """
  1642. Set the color limits of the current image.
  1643. To apply clim to all axes images do::
  1644. clim(0, 0.5)
  1645. If either *vmin* or *vmax* is None, the image min/max respectively
  1646. will be used for color scaling.
  1647. If you want to set the clim of multiple images,
  1648. use, for example::
  1649. for im in gca().get_images():
  1650. im.set_clim(0, 0.05)
  1651. """
  1652. im = gci()
  1653. if im is None:
  1654. raise RuntimeError('You must first define an image, e.g., with imshow')
  1655. im.set_clim(vmin, vmax)
  1656. def set_cmap(cmap):
  1657. """
  1658. Set the default colormap. Applies to the current image if any.
  1659. See help(colormaps) for more information.
  1660. *cmap* must be a :class:`~matplotlib.colors.Colormap` instance, or
  1661. the name of a registered colormap.
  1662. See :func:`matplotlib.cm.register_cmap` and
  1663. :func:`matplotlib.cm.get_cmap`.
  1664. """
  1665. cmap = cm.get_cmap(cmap)
  1666. rc('image', cmap=cmap.name)
  1667. im = gci()
  1668. if im is not None:
  1669. im.set_cmap(cmap)
  1670. @docstring.copy_dedent(matplotlib.image.imread)
  1671. def imread(fname, format=None):
  1672. return matplotlib.image.imread(fname, format)
  1673. @docstring.copy_dedent(matplotlib.image.imsave)
  1674. def imsave(fname, arr, **kwargs):
  1675. return matplotlib.image.imsave(fname, arr, **kwargs)
  1676. def matshow(A, fignum=None, **kwargs):
  1677. """
  1678. Display an array as a matrix in a new figure window.
  1679. The origin is set at the upper left hand corner and rows (first
  1680. dimension of the array) are displayed horizontally. The aspect
  1681. ratio of the figure window is that of the array, unless this would
  1682. make an excessively short or narrow figure.
  1683. Tick labels for the xaxis are placed on top.
  1684. Parameters
  1685. ----------
  1686. A : array-like(M, N)
  1687. The matrix to be displayed.
  1688. fignum : None or int or False
  1689. If *None*, create a new figure window with automatic numbering.
  1690. If *fignum* is an integer, draw into the figure with the given number
  1691. (create it if it does not exist).
  1692. If 0 or *False*, use the current axes if it exists instead of creating
  1693. a new figure.
  1694. .. note::
  1695. Because of how `.Axes.matshow` tries to set the figure aspect
  1696. ratio to be the one of the array, strange things may happen if you
  1697. reuse an existing figure.
  1698. Returns
  1699. -------
  1700. image : `~matplotlib.image.AxesImage`
  1701. Other Parameters
  1702. ----------------
  1703. **kwargs : `~matplotlib.axes.Axes.imshow` arguments
  1704. """
  1705. A = np.asanyarray(A)
  1706. if fignum is False or fignum is 0:
  1707. ax = gca()
  1708. else:
  1709. # Extract actual aspect ratio of array and make appropriately sized figure
  1710. fig = figure(fignum, figsize=figaspect(A))
  1711. ax = fig.add_axes([0.15, 0.09, 0.775, 0.775])
  1712. im = ax.matshow(A, **kwargs)
  1713. sci(im)
  1714. return im
  1715. def polar(*args, **kwargs):
  1716. """
  1717. Make a polar plot.
  1718. call signature::
  1719. polar(theta, r, **kwargs)
  1720. Multiple *theta*, *r* arguments are supported, with format
  1721. strings, as in :func:`~matplotlib.pyplot.plot`.
  1722. """
  1723. # If an axis already exists, check if it has a polar projection
  1724. if gcf().get_axes():
  1725. if not isinstance(gca(), PolarAxes):
  1726. warnings.warn('Trying to create polar plot on an axis that does '
  1727. 'not have a polar projection.')
  1728. ax = gca(polar=True)
  1729. ret = ax.plot(*args, **kwargs)
  1730. return ret
  1731. def plotfile(fname, cols=(0,), plotfuncs=None,
  1732. comments='#', skiprows=0, checkrows=5, delimiter=',',
  1733. names=None, subplots=True, newfig=True, **kwargs):
  1734. """
  1735. Plot the data in a file.
  1736. *cols* is a sequence of column identifiers to plot. An identifier
  1737. is either an int or a string. If it is an int, it indicates the
  1738. column number. If it is a string, it indicates the column header.
  1739. matplotlib will make column headers lower case, replace spaces with
  1740. underscores, and remove all illegal characters; so ``'Adj Close*'``
  1741. will have name ``'adj_close'``.
  1742. - If len(*cols*) == 1, only that column will be plotted on the *y* axis.
  1743. - If len(*cols*) > 1, the first element will be an identifier for
  1744. data for the *x* axis and the remaining elements will be the
  1745. column indexes for multiple subplots if *subplots* is *True*
  1746. (the default), or for lines in a single subplot if *subplots*
  1747. is *False*.
  1748. *plotfuncs*, if not *None*, is a dictionary mapping identifier to
  1749. an :class:`~matplotlib.axes.Axes` plotting function as a string.
  1750. Default is 'plot', other choices are 'semilogy', 'fill', 'bar',
  1751. etc. You must use the same type of identifier in the *cols*
  1752. vector as you use in the *plotfuncs* dictionary, e.g., integer
  1753. column numbers in both or column names in both. If *subplots*
  1754. is *False*, then including any function such as 'semilogy'
  1755. that changes the axis scaling will set the scaling for all
  1756. columns.
  1757. *comments*, *skiprows*, *checkrows*, *delimiter*, and *names*
  1758. are all passed on to :func:`matplotlib.mlab.csv2rec` to
  1759. load the data into a record array.
  1760. If *newfig* is *True*, the plot always will be made in a new figure;
  1761. if *False*, it will be made in the current figure if one exists,
  1762. else in a new figure.
  1763. kwargs are passed on to plotting functions.
  1764. Example usage::
  1765. # plot the 2nd and 4th column against the 1st in two subplots
  1766. plotfile(fname, (0,1,3))
  1767. # plot using column names; specify an alternate plot type for volume
  1768. plotfile(fname, ('date', 'volume', 'adj_close'),
  1769. plotfuncs={'volume': 'semilogy'})
  1770. Note: plotfile is intended as a convenience for quickly plotting
  1771. data from flat files; it is not intended as an alternative
  1772. interface to general plotting with pyplot or matplotlib.
  1773. """
  1774. if newfig:
  1775. fig = figure()
  1776. else:
  1777. fig = gcf()
  1778. if len(cols)<1:
  1779. raise ValueError('must have at least one column of data')
  1780. if plotfuncs is None:
  1781. plotfuncs = dict()
  1782. from matplotlib.cbook import MatplotlibDeprecationWarning
  1783. with warnings.catch_warnings():
  1784. warnings.simplefilter('ignore', MatplotlibDeprecationWarning)
  1785. r = mlab.csv2rec(fname, comments=comments, skiprows=skiprows,
  1786. checkrows=checkrows, delimiter=delimiter, names=names)
  1787. def getname_val(identifier):
  1788. 'return the name and column data for identifier'
  1789. if isinstance(identifier, str):
  1790. return identifier, r[identifier]
  1791. elif isinstance(identifier, Number):
  1792. name = r.dtype.names[int(identifier)]
  1793. return name, r[name]
  1794. else:
  1795. raise TypeError('identifier must be a string or integer')
  1796. xname, x = getname_val(cols[0])
  1797. ynamelist = []
  1798. if len(cols)==1:
  1799. ax1 = fig.add_subplot(1,1,1)
  1800. funcname = plotfuncs.get(cols[0], 'plot')
  1801. func = getattr(ax1, funcname)
  1802. func(x, **kwargs)
  1803. ax1.set_ylabel(xname)
  1804. else:
  1805. N = len(cols)
  1806. for i in range(1,N):
  1807. if subplots:
  1808. if i==1:
  1809. ax = ax1 = fig.add_subplot(N-1,1,i)
  1810. else:
  1811. ax = fig.add_subplot(N-1,1,i, sharex=ax1)
  1812. elif i==1:
  1813. ax = fig.add_subplot(1,1,1)
  1814. yname, y = getname_val(cols[i])
  1815. ynamelist.append(yname)
  1816. funcname = plotfuncs.get(cols[i], 'plot')
  1817. func = getattr(ax, funcname)
  1818. func(x, y, **kwargs)
  1819. if subplots:
  1820. ax.set_ylabel(yname)
  1821. if ax.is_last_row():
  1822. ax.set_xlabel(xname)
  1823. else:
  1824. ax.set_xlabel('')
  1825. if not subplots:
  1826. ax.legend(ynamelist)
  1827. if xname=='date':
  1828. fig.autofmt_xdate()
  1829. def _autogen_docstring(base):
  1830. """Autogenerated wrappers will get their docstring from a base function
  1831. with an addendum."""
  1832. msg = ''
  1833. addendum = docstring.Appender(msg, '\n\n')
  1834. return lambda func: addendum(docstring.copy_dedent(base)(func))
  1835. # If rcParams['backend_fallback'] is true, and an interactive backend is
  1836. # requested, ignore rcParams['backend'] and force selection of a backend that
  1837. # is compatible with the current running interactive framework.
  1838. if (rcParams["backend_fallback"]
  1839. and dict.__getitem__(rcParams, "backend") in _interactive_bk
  1840. and _get_running_interactive_framework()):
  1841. dict.__setitem__(rcParams, "backend", rcsetup._auto_backend_sentinel)
  1842. # Set up the backend.
  1843. switch_backend(rcParams["backend"])
  1844. # Just to be safe. Interactive mode can be turned on without
  1845. # calling `plt.ion()` so register it again here.
  1846. # This is safe because multiple calls to `install_repl_displayhook`
  1847. # are no-ops and the registered function respect `mpl.is_interactive()`
  1848. # to determine if they should trigger a draw.
  1849. install_repl_displayhook()
  1850. ################# REMAINING CONTENT GENERATED BY boilerplate.py ##############
  1851. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  1852. @docstring.copy_dedent(Axes.acorr)
  1853. def acorr(x, *, data=None, **kwargs):
  1854. return gca().acorr(
  1855. x, **({"data": data} if data is not None else {}), **kwargs)
  1856. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  1857. @docstring.copy_dedent(Axes.angle_spectrum)
  1858. def angle_spectrum(
  1859. x, Fs=None, Fc=None, window=None, pad_to=None, sides=None, *,
  1860. data=None, **kwargs):
  1861. return gca().angle_spectrum(
  1862. x, Fs=Fs, Fc=Fc, window=window, pad_to=pad_to, sides=sides,
  1863. **({"data": data} if data is not None else {}), **kwargs)
  1864. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  1865. @docstring.copy_dedent(Axes.annotate)
  1866. def annotate(s, xy, *args, **kwargs):
  1867. return gca().annotate(s, xy, *args, **kwargs)
  1868. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  1869. @docstring.copy_dedent(Axes.arrow)
  1870. def arrow(x, y, dx, dy, **kwargs):
  1871. return gca().arrow(x, y, dx, dy, **kwargs)
  1872. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  1873. @docstring.copy_dedent(Axes.autoscale)
  1874. def autoscale(enable=True, axis='both', tight=None):
  1875. return gca().autoscale(enable=enable, axis=axis, tight=tight)
  1876. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  1877. @docstring.copy_dedent(Axes.axhline)
  1878. def axhline(y=0, xmin=0, xmax=1, **kwargs):
  1879. return gca().axhline(y=y, xmin=xmin, xmax=xmax, **kwargs)
  1880. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  1881. @docstring.copy_dedent(Axes.axhspan)
  1882. def axhspan(ymin, ymax, xmin=0, xmax=1, **kwargs):
  1883. return gca().axhspan(ymin, ymax, xmin=xmin, xmax=xmax, **kwargs)
  1884. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  1885. @docstring.copy_dedent(Axes.axis)
  1886. def axis(*v, **kwargs):
  1887. return gca().axis(*v, **kwargs)
  1888. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  1889. @docstring.copy_dedent(Axes.axvline)
  1890. def axvline(x=0, ymin=0, ymax=1, **kwargs):
  1891. return gca().axvline(x=x, ymin=ymin, ymax=ymax, **kwargs)
  1892. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  1893. @docstring.copy_dedent(Axes.axvspan)
  1894. def axvspan(xmin, xmax, ymin=0, ymax=1, **kwargs):
  1895. return gca().axvspan(xmin, xmax, ymin=ymin, ymax=ymax, **kwargs)
  1896. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  1897. @docstring.copy_dedent(Axes.bar)
  1898. def bar(
  1899. x, height, width=0.8, bottom=None, *, align='center',
  1900. data=None, **kwargs):
  1901. return gca().bar(
  1902. x, height, width=width, bottom=bottom, align=align,
  1903. **({"data": data} if data is not None else {}), **kwargs)
  1904. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  1905. @docstring.copy_dedent(Axes.barbs)
  1906. def barbs(*args, data=None, **kw):
  1907. return gca().barbs(
  1908. *args, **({"data": data} if data is not None else {}), **kw)
  1909. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  1910. @docstring.copy_dedent(Axes.barh)
  1911. def barh(y, width, height=0.8, left=None, *, align='center', **kwargs):
  1912. return gca().barh(
  1913. y, width, height=height, left=left, align=align, **kwargs)
  1914. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  1915. @docstring.copy_dedent(Axes.boxplot)
  1916. def boxplot(
  1917. x, notch=None, sym=None, vert=None, whis=None,
  1918. positions=None, widths=None, patch_artist=None,
  1919. bootstrap=None, usermedians=None, conf_intervals=None,
  1920. meanline=None, showmeans=None, showcaps=None, showbox=None,
  1921. showfliers=None, boxprops=None, labels=None, flierprops=None,
  1922. medianprops=None, meanprops=None, capprops=None,
  1923. whiskerprops=None, manage_xticks=True, autorange=False,
  1924. zorder=None, *, data=None):
  1925. return gca().boxplot(
  1926. x, notch=notch, sym=sym, vert=vert, whis=whis,
  1927. positions=positions, widths=widths, patch_artist=patch_artist,
  1928. bootstrap=bootstrap, usermedians=usermedians,
  1929. conf_intervals=conf_intervals, meanline=meanline,
  1930. showmeans=showmeans, showcaps=showcaps, showbox=showbox,
  1931. showfliers=showfliers, boxprops=boxprops, labels=labels,
  1932. flierprops=flierprops, medianprops=medianprops,
  1933. meanprops=meanprops, capprops=capprops,
  1934. whiskerprops=whiskerprops, manage_xticks=manage_xticks,
  1935. autorange=autorange, zorder=zorder, **({"data": data} if data
  1936. is not None else {}))
  1937. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  1938. @docstring.copy_dedent(Axes.broken_barh)
  1939. def broken_barh(xranges, yrange, *, data=None, **kwargs):
  1940. return gca().broken_barh(
  1941. xranges, yrange, **({"data": data} if data is not None else
  1942. {}), **kwargs)
  1943. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  1944. @docstring.copy_dedent(Axes.cla)
  1945. def cla():
  1946. return gca().cla()
  1947. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  1948. @docstring.copy_dedent(Axes.clabel)
  1949. def clabel(CS, *args, **kwargs):
  1950. return gca().clabel(CS, *args, **kwargs)
  1951. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  1952. @docstring.copy_dedent(Axes.cohere)
  1953. def cohere(
  1954. x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
  1955. window=mlab.window_hanning, noverlap=0, pad_to=None,
  1956. sides='default', scale_by_freq=None, *, data=None, **kwargs):
  1957. return gca().cohere(
  1958. x, y, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, window=window,
  1959. noverlap=noverlap, pad_to=pad_to, sides=sides,
  1960. scale_by_freq=scale_by_freq, **({"data": data} if data is not
  1961. None else {}), **kwargs)
  1962. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  1963. @_autogen_docstring(Axes.contour)
  1964. def contour(*args, data=None, **kwargs):
  1965. __ret = gca().contour(
  1966. *args, **({"data": data} if data is not None else {}),
  1967. **kwargs)
  1968. if __ret._A is not None: sci(__ret) # noqa
  1969. return __ret
  1970. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  1971. @_autogen_docstring(Axes.contourf)
  1972. def contourf(*args, data=None, **kwargs):
  1973. __ret = gca().contourf(
  1974. *args, **({"data": data} if data is not None else {}),
  1975. **kwargs)
  1976. if __ret._A is not None: sci(__ret) # noqa
  1977. return __ret
  1978. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  1979. @docstring.copy_dedent(Axes.csd)
  1980. def csd(
  1981. x, y, NFFT=None, Fs=None, Fc=None, detrend=None, window=None,
  1982. noverlap=None, pad_to=None, sides=None, scale_by_freq=None,
  1983. return_line=None, *, data=None, **kwargs):
  1984. return gca().csd(
  1985. x, y, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, window=window,
  1986. noverlap=noverlap, pad_to=pad_to, sides=sides,
  1987. scale_by_freq=scale_by_freq, return_line=return_line,
  1988. **({"data": data} if data is not None else {}), **kwargs)
  1989. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  1990. @docstring.copy_dedent(Axes.errorbar)
  1991. def errorbar(
  1992. x, y, yerr=None, xerr=None, fmt='', ecolor=None,
  1993. elinewidth=None, capsize=None, barsabove=False, lolims=False,
  1994. uplims=False, xlolims=False, xuplims=False, errorevery=1,
  1995. capthick=None, *, data=None, **kwargs):
  1996. return gca().errorbar(
  1997. x, y, yerr=yerr, xerr=xerr, fmt=fmt, ecolor=ecolor,
  1998. elinewidth=elinewidth, capsize=capsize, barsabove=barsabove,
  1999. lolims=lolims, uplims=uplims, xlolims=xlolims,
  2000. xuplims=xuplims, errorevery=errorevery, capthick=capthick,
  2001. **({"data": data} if data is not None else {}), **kwargs)
  2002. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2003. @docstring.copy_dedent(Axes.eventplot)
  2004. def eventplot(
  2005. positions, orientation='horizontal', lineoffsets=1,
  2006. linelengths=1, linewidths=None, colors=None,
  2007. linestyles='solid', *, data=None, **kwargs):
  2008. return gca().eventplot(
  2009. positions, orientation=orientation, lineoffsets=lineoffsets,
  2010. linelengths=linelengths, linewidths=linewidths, colors=colors,
  2011. linestyles=linestyles, **({"data": data} if data is not None
  2012. else {}), **kwargs)
  2013. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2014. @docstring.copy_dedent(Axes.fill)
  2015. def fill(*args, data=None, **kwargs):
  2016. return gca().fill(
  2017. *args, **({"data": data} if data is not None else {}),
  2018. **kwargs)
  2019. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2020. @docstring.copy_dedent(Axes.fill_between)
  2021. def fill_between(
  2022. x, y1, y2=0, where=None, interpolate=False, step=None, *,
  2023. data=None, **kwargs):
  2024. return gca().fill_between(
  2025. x, y1, y2=y2, where=where, interpolate=interpolate, step=step,
  2026. **({"data": data} if data is not None else {}), **kwargs)
  2027. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2028. @docstring.copy_dedent(Axes.fill_betweenx)
  2029. def fill_betweenx(
  2030. y, x1, x2=0, where=None, step=None, interpolate=False, *,
  2031. data=None, **kwargs):
  2032. return gca().fill_betweenx(
  2033. y, x1, x2=x2, where=where, step=step, interpolate=interpolate,
  2034. **({"data": data} if data is not None else {}), **kwargs)
  2035. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2036. @docstring.copy_dedent(Axes.grid)
  2037. def grid(b=None, which='major', axis='both', **kwargs):
  2038. return gca().grid(b=b, which=which, axis=axis, **kwargs)
  2039. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2040. @_autogen_docstring(Axes.hexbin)
  2041. def hexbin(
  2042. x, y, C=None, gridsize=100, bins=None, xscale='linear',
  2043. yscale='linear', extent=None, cmap=None, norm=None, vmin=None,
  2044. vmax=None, alpha=None, linewidths=None, edgecolors='face',
  2045. reduce_C_function=np.mean, mincnt=None, marginals=False, *,
  2046. data=None, **kwargs):
  2047. __ret = gca().hexbin(
  2048. x, y, C=C, gridsize=gridsize, bins=bins, xscale=xscale,
  2049. yscale=yscale, extent=extent, cmap=cmap, norm=norm, vmin=vmin,
  2050. vmax=vmax, alpha=alpha, linewidths=linewidths,
  2051. edgecolors=edgecolors, reduce_C_function=reduce_C_function,
  2052. mincnt=mincnt, marginals=marginals, **({"data": data} if data
  2053. is not None else {}), **kwargs)
  2054. sci(__ret)
  2055. return __ret
  2056. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2057. @docstring.copy_dedent(Axes.hist)
  2058. def hist(
  2059. x, bins=None, range=None, density=None, weights=None,
  2060. cumulative=False, bottom=None, histtype='bar', align='mid',
  2061. orientation='vertical', rwidth=None, log=False, color=None,
  2062. label=None, stacked=False, normed=None, *, data=None,
  2063. **kwargs):
  2064. return gca().hist(
  2065. x, bins=bins, range=range, density=density, weights=weights,
  2066. cumulative=cumulative, bottom=bottom, histtype=histtype,
  2067. align=align, orientation=orientation, rwidth=rwidth, log=log,
  2068. color=color, label=label, stacked=stacked, normed=normed,
  2069. **({"data": data} if data is not None else {}), **kwargs)
  2070. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2071. @_autogen_docstring(Axes.hist2d)
  2072. def hist2d(
  2073. x, y, bins=10, range=None, normed=False, weights=None,
  2074. cmin=None, cmax=None, *, data=None, **kwargs):
  2075. __ret = gca().hist2d(
  2076. x, y, bins=bins, range=range, normed=normed, weights=weights,
  2077. cmin=cmin, cmax=cmax, **({"data": data} if data is not None
  2078. else {}), **kwargs)
  2079. sci(__ret[-1])
  2080. return __ret
  2081. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2082. @docstring.copy_dedent(Axes.hlines)
  2083. def hlines(
  2084. y, xmin, xmax, colors='k', linestyles='solid', label='', *,
  2085. data=None, **kwargs):
  2086. return gca().hlines(
  2087. y, xmin, xmax, colors=colors, linestyles=linestyles,
  2088. label=label, **({"data": data} if data is not None else {}),
  2089. **kwargs)
  2090. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2091. @_autogen_docstring(Axes.imshow)
  2092. def imshow(
  2093. X, cmap=None, norm=None, aspect=None, interpolation=None,
  2094. alpha=None, vmin=None, vmax=None, origin=None, extent=None,
  2095. shape=None, filternorm=1, filterrad=4.0, imlim=None,
  2096. resample=None, url=None, *, data=None, **kwargs):
  2097. __ret = gca().imshow(
  2098. X, cmap=cmap, norm=norm, aspect=aspect,
  2099. interpolation=interpolation, alpha=alpha, vmin=vmin,
  2100. vmax=vmax, origin=origin, extent=extent, shape=shape,
  2101. filternorm=filternorm, filterrad=filterrad, imlim=imlim,
  2102. resample=resample, url=url, **({"data": data} if data is not
  2103. None else {}), **kwargs)
  2104. sci(__ret)
  2105. return __ret
  2106. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2107. @docstring.copy_dedent(Axes.legend)
  2108. def legend(*args, **kwargs):
  2109. return gca().legend(*args, **kwargs)
  2110. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2111. @docstring.copy_dedent(Axes.locator_params)
  2112. def locator_params(axis='both', tight=None, **kwargs):
  2113. return gca().locator_params(axis=axis, tight=tight, **kwargs)
  2114. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2115. @docstring.copy_dedent(Axes.loglog)
  2116. def loglog(*args, **kwargs):
  2117. return gca().loglog(*args, **kwargs)
  2118. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2119. @docstring.copy_dedent(Axes.magnitude_spectrum)
  2120. def magnitude_spectrum(
  2121. x, Fs=None, Fc=None, window=None, pad_to=None, sides=None,
  2122. scale=None, *, data=None, **kwargs):
  2123. return gca().magnitude_spectrum(
  2124. x, Fs=Fs, Fc=Fc, window=window, pad_to=pad_to, sides=sides,
  2125. scale=scale, **({"data": data} if data is not None else {}),
  2126. **kwargs)
  2127. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2128. @docstring.copy_dedent(Axes.margins)
  2129. def margins(*margins, x=None, y=None, tight=True):
  2130. return gca().margins(*margins, x=x, y=y, tight=tight)
  2131. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2132. @docstring.copy_dedent(Axes.minorticks_off)
  2133. def minorticks_off():
  2134. return gca().minorticks_off()
  2135. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2136. @docstring.copy_dedent(Axes.minorticks_on)
  2137. def minorticks_on():
  2138. return gca().minorticks_on()
  2139. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2140. @_autogen_docstring(Axes.pcolor)
  2141. def pcolor(
  2142. *args, alpha=None, norm=None, cmap=None, vmin=None,
  2143. vmax=None, data=None, **kwargs):
  2144. __ret = gca().pcolor(
  2145. *args, alpha=alpha, norm=norm, cmap=cmap, vmin=vmin,
  2146. vmax=vmax, **({"data": data} if data is not None else {}),
  2147. **kwargs)
  2148. sci(__ret)
  2149. return __ret
  2150. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2151. @_autogen_docstring(Axes.pcolormesh)
  2152. def pcolormesh(
  2153. *args, alpha=None, norm=None, cmap=None, vmin=None,
  2154. vmax=None, shading='flat', antialiased=False, data=None,
  2155. **kwargs):
  2156. __ret = gca().pcolormesh(
  2157. *args, alpha=alpha, norm=norm, cmap=cmap, vmin=vmin,
  2158. vmax=vmax, shading=shading, antialiased=antialiased,
  2159. **({"data": data} if data is not None else {}), **kwargs)
  2160. sci(__ret)
  2161. return __ret
  2162. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2163. @docstring.copy_dedent(Axes.phase_spectrum)
  2164. def phase_spectrum(
  2165. x, Fs=None, Fc=None, window=None, pad_to=None, sides=None, *,
  2166. data=None, **kwargs):
  2167. return gca().phase_spectrum(
  2168. x, Fs=Fs, Fc=Fc, window=window, pad_to=pad_to, sides=sides,
  2169. **({"data": data} if data is not None else {}), **kwargs)
  2170. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2171. @docstring.copy_dedent(Axes.pie)
  2172. def pie(
  2173. x, explode=None, labels=None, colors=None, autopct=None,
  2174. pctdistance=0.6, shadow=False, labeldistance=1.1,
  2175. startangle=None, radius=None, counterclock=True,
  2176. wedgeprops=None, textprops=None, center=(0, 0), frame=False,
  2177. rotatelabels=False, *, data=None):
  2178. return gca().pie(
  2179. x, explode=explode, labels=labels, colors=colors,
  2180. autopct=autopct, pctdistance=pctdistance, shadow=shadow,
  2181. labeldistance=labeldistance, startangle=startangle,
  2182. radius=radius, counterclock=counterclock,
  2183. wedgeprops=wedgeprops, textprops=textprops, center=center,
  2184. frame=frame, rotatelabels=rotatelabels, **({"data": data} if
  2185. data is not None else {}))
  2186. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2187. @docstring.copy_dedent(Axes.plot)
  2188. def plot(*args, scalex=True, scaley=True, data=None, **kwargs):
  2189. return gca().plot(
  2190. *args, scalex=scalex, scaley=scaley, **({"data": data} if data
  2191. is not None else {}), **kwargs)
  2192. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2193. @docstring.copy_dedent(Axes.plot_date)
  2194. def plot_date(
  2195. x, y, fmt='o', tz=None, xdate=True, ydate=False, *,
  2196. data=None, **kwargs):
  2197. return gca().plot_date(
  2198. x, y, fmt=fmt, tz=tz, xdate=xdate, ydate=ydate, **({"data":
  2199. data} if data is not None else {}), **kwargs)
  2200. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2201. @docstring.copy_dedent(Axes.psd)
  2202. def psd(
  2203. x, NFFT=None, Fs=None, Fc=None, detrend=None, window=None,
  2204. noverlap=None, pad_to=None, sides=None, scale_by_freq=None,
  2205. return_line=None, *, data=None, **kwargs):
  2206. return gca().psd(
  2207. x, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, window=window,
  2208. noverlap=noverlap, pad_to=pad_to, sides=sides,
  2209. scale_by_freq=scale_by_freq, return_line=return_line,
  2210. **({"data": data} if data is not None else {}), **kwargs)
  2211. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2212. @_autogen_docstring(Axes.quiver)
  2213. def quiver(*args, data=None, **kw):
  2214. __ret = gca().quiver(
  2215. *args, **({"data": data} if data is not None else {}), **kw)
  2216. sci(__ret)
  2217. return __ret
  2218. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2219. @docstring.copy_dedent(Axes.quiverkey)
  2220. def quiverkey(Q, X, Y, U, label, **kw):
  2221. return gca().quiverkey(Q, X, Y, U, label, **kw)
  2222. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2223. @_autogen_docstring(Axes.scatter)
  2224. def scatter(
  2225. x, y, s=None, c=None, marker=None, cmap=None, norm=None,
  2226. vmin=None, vmax=None, alpha=None, linewidths=None, verts=None,
  2227. edgecolors=None, *, data=None, **kwargs):
  2228. __ret = gca().scatter(
  2229. x, y, s=s, c=c, marker=marker, cmap=cmap, norm=norm,
  2230. vmin=vmin, vmax=vmax, alpha=alpha, linewidths=linewidths,
  2231. verts=verts, edgecolors=edgecolors, **({"data": data} if data
  2232. is not None else {}), **kwargs)
  2233. sci(__ret)
  2234. return __ret
  2235. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2236. @docstring.copy_dedent(Axes.semilogx)
  2237. def semilogx(*args, **kwargs):
  2238. return gca().semilogx(*args, **kwargs)
  2239. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2240. @docstring.copy_dedent(Axes.semilogy)
  2241. def semilogy(*args, **kwargs):
  2242. return gca().semilogy(*args, **kwargs)
  2243. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2244. @_autogen_docstring(Axes.specgram)
  2245. def specgram(
  2246. x, NFFT=None, Fs=None, Fc=None, detrend=None, window=None,
  2247. noverlap=None, cmap=None, xextent=None, pad_to=None,
  2248. sides=None, scale_by_freq=None, mode=None, scale=None,
  2249. vmin=None, vmax=None, *, data=None, **kwargs):
  2250. __ret = gca().specgram(
  2251. x, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, window=window,
  2252. noverlap=noverlap, cmap=cmap, xextent=xextent, pad_to=pad_to,
  2253. sides=sides, scale_by_freq=scale_by_freq, mode=mode,
  2254. scale=scale, vmin=vmin, vmax=vmax, **({"data": data} if data
  2255. is not None else {}), **kwargs)
  2256. sci(__ret[-1])
  2257. return __ret
  2258. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2259. @_autogen_docstring(Axes.spy)
  2260. def spy(
  2261. Z, precision=0, marker=None, markersize=None, aspect='equal',
  2262. origin='upper', **kwargs):
  2263. __ret = gca().spy(
  2264. Z, precision=precision, marker=marker, markersize=markersize,
  2265. aspect=aspect, origin=origin, **kwargs)
  2266. if isinstance(__ret, cm.ScalarMappable): sci(__ret) # noqa
  2267. return __ret
  2268. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2269. @docstring.copy_dedent(Axes.stackplot)
  2270. def stackplot(x, *args, data=None, **kwargs):
  2271. return gca().stackplot(
  2272. x, *args, **({"data": data} if data is not None else {}),
  2273. **kwargs)
  2274. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2275. @docstring.copy_dedent(Axes.stem)
  2276. def stem(
  2277. *args, linefmt=None, markerfmt=None, basefmt=None, bottom=0,
  2278. label=None, data=None):
  2279. return gca().stem(
  2280. *args, linefmt=linefmt, markerfmt=markerfmt, basefmt=basefmt,
  2281. bottom=bottom, label=label, **({"data": data} if data is not
  2282. None else {}))
  2283. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2284. @docstring.copy_dedent(Axes.step)
  2285. def step(x, y, *args, where='pre', data=None, **kwargs):
  2286. return gca().step(
  2287. x, y, *args, where=where, **({"data": data} if data is not
  2288. None else {}), **kwargs)
  2289. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2290. @_autogen_docstring(Axes.streamplot)
  2291. def streamplot(
  2292. x, y, u, v, density=1, linewidth=None, color=None, cmap=None,
  2293. norm=None, arrowsize=1, arrowstyle='-|>', minlength=0.1,
  2294. transform=None, zorder=None, start_points=None, maxlength=4.0,
  2295. integration_direction='both', *, data=None):
  2296. __ret = gca().streamplot(
  2297. x, y, u, v, density=density, linewidth=linewidth, color=color,
  2298. cmap=cmap, norm=norm, arrowsize=arrowsize,
  2299. arrowstyle=arrowstyle, minlength=minlength,
  2300. transform=transform, zorder=zorder, start_points=start_points,
  2301. maxlength=maxlength,
  2302. integration_direction=integration_direction, **({"data": data}
  2303. if data is not None else {}))
  2304. sci(__ret.lines)
  2305. return __ret
  2306. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2307. @docstring.copy_dedent(Axes.table)
  2308. def table(**kwargs):
  2309. return gca().table(**kwargs)
  2310. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2311. @docstring.copy_dedent(Axes.text)
  2312. def text(x, y, s, fontdict=None, withdash=False, **kwargs):
  2313. return gca().text(x, y, s, fontdict=fontdict, withdash=withdash, **kwargs)
  2314. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2315. @docstring.copy_dedent(Axes.tick_params)
  2316. def tick_params(axis='both', **kwargs):
  2317. return gca().tick_params(axis=axis, **kwargs)
  2318. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2319. @docstring.copy_dedent(Axes.ticklabel_format)
  2320. def ticklabel_format(
  2321. *, axis='both', style='', scilimits=None, useOffset=None,
  2322. useLocale=None, useMathText=None):
  2323. return gca().ticklabel_format(
  2324. axis=axis, style=style, scilimits=scilimits,
  2325. useOffset=useOffset, useLocale=useLocale,
  2326. useMathText=useMathText)
  2327. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2328. @_autogen_docstring(Axes.tricontour)
  2329. def tricontour(*args, **kwargs):
  2330. __ret = gca().tricontour(*args, **kwargs)
  2331. if __ret._A is not None: sci(__ret) # noqa
  2332. return __ret
  2333. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2334. @_autogen_docstring(Axes.tricontourf)
  2335. def tricontourf(*args, **kwargs):
  2336. __ret = gca().tricontourf(*args, **kwargs)
  2337. if __ret._A is not None: sci(__ret) # noqa
  2338. return __ret
  2339. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2340. @_autogen_docstring(Axes.tripcolor)
  2341. def tripcolor(*args, **kwargs):
  2342. __ret = gca().tripcolor(*args, **kwargs)
  2343. sci(__ret)
  2344. return __ret
  2345. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2346. @docstring.copy_dedent(Axes.triplot)
  2347. def triplot(*args, **kwargs):
  2348. return gca().triplot(*args, **kwargs)
  2349. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2350. @docstring.copy_dedent(Axes.violinplot)
  2351. def violinplot(
  2352. dataset, positions=None, vert=True, widths=0.5,
  2353. showmeans=False, showextrema=True, showmedians=False,
  2354. points=100, bw_method=None, *, data=None):
  2355. return gca().violinplot(
  2356. dataset, positions=positions, vert=vert, widths=widths,
  2357. showmeans=showmeans, showextrema=showextrema,
  2358. showmedians=showmedians, points=points, bw_method=bw_method,
  2359. **({"data": data} if data is not None else {}))
  2360. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2361. @docstring.copy_dedent(Axes.vlines)
  2362. def vlines(
  2363. x, ymin, ymax, colors='k', linestyles='solid', label='', *,
  2364. data=None, **kwargs):
  2365. return gca().vlines(
  2366. x, ymin, ymax, colors=colors, linestyles=linestyles,
  2367. label=label, **({"data": data} if data is not None else {}),
  2368. **kwargs)
  2369. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2370. @docstring.copy_dedent(Axes.xcorr)
  2371. def xcorr(
  2372. x, y, normed=True, detrend=mlab.detrend_none, usevlines=True,
  2373. maxlags=10, *, data=None, **kwargs):
  2374. return gca().xcorr(
  2375. x, y, normed=normed, detrend=detrend, usevlines=usevlines,
  2376. maxlags=maxlags, **({"data": data} if data is not None else
  2377. {}), **kwargs)
  2378. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2379. @docstring.copy_dedent(Axes._sci)
  2380. def sci(im):
  2381. return gca()._sci(im)
  2382. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2383. @docstring.copy_dedent(Axes.set_title)
  2384. def title(label, fontdict=None, loc='center', pad=None, **kwargs):
  2385. return gca().set_title(
  2386. label, fontdict=fontdict, loc=loc, pad=pad, **kwargs)
  2387. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2388. @docstring.copy_dedent(Axes.set_xlabel)
  2389. def xlabel(xlabel, fontdict=None, labelpad=None, **kwargs):
  2390. return gca().set_xlabel(
  2391. xlabel, fontdict=fontdict, labelpad=labelpad, **kwargs)
  2392. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2393. @docstring.copy_dedent(Axes.set_ylabel)
  2394. def ylabel(ylabel, fontdict=None, labelpad=None, **kwargs):
  2395. return gca().set_ylabel(
  2396. ylabel, fontdict=fontdict, labelpad=labelpad, **kwargs)
  2397. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2398. @docstring.copy_dedent(Axes.set_xscale)
  2399. def xscale(value, **kwargs):
  2400. return gca().set_xscale(value, **kwargs)
  2401. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2402. @docstring.copy_dedent(Axes.set_yscale)
  2403. def yscale(value, **kwargs):
  2404. return gca().set_yscale(value, **kwargs)
  2405. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2406. def autumn():
  2407. """
  2408. Set the colormap to "autumn".
  2409. This changes the default colormap as well as the colormap of the current
  2410. image if there is one. See ``help(colormaps)`` for more information.
  2411. """
  2412. set_cmap("autumn")
  2413. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2414. def bone():
  2415. """
  2416. Set the colormap to "bone".
  2417. This changes the default colormap as well as the colormap of the current
  2418. image if there is one. See ``help(colormaps)`` for more information.
  2419. """
  2420. set_cmap("bone")
  2421. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2422. def cool():
  2423. """
  2424. Set the colormap to "cool".
  2425. This changes the default colormap as well as the colormap of the current
  2426. image if there is one. See ``help(colormaps)`` for more information.
  2427. """
  2428. set_cmap("cool")
  2429. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2430. def copper():
  2431. """
  2432. Set the colormap to "copper".
  2433. This changes the default colormap as well as the colormap of the current
  2434. image if there is one. See ``help(colormaps)`` for more information.
  2435. """
  2436. set_cmap("copper")
  2437. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2438. def flag():
  2439. """
  2440. Set the colormap to "flag".
  2441. This changes the default colormap as well as the colormap of the current
  2442. image if there is one. See ``help(colormaps)`` for more information.
  2443. """
  2444. set_cmap("flag")
  2445. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2446. def gray():
  2447. """
  2448. Set the colormap to "gray".
  2449. This changes the default colormap as well as the colormap of the current
  2450. image if there is one. See ``help(colormaps)`` for more information.
  2451. """
  2452. set_cmap("gray")
  2453. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2454. def hot():
  2455. """
  2456. Set the colormap to "hot".
  2457. This changes the default colormap as well as the colormap of the current
  2458. image if there is one. See ``help(colormaps)`` for more information.
  2459. """
  2460. set_cmap("hot")
  2461. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2462. def hsv():
  2463. """
  2464. Set the colormap to "hsv".
  2465. This changes the default colormap as well as the colormap of the current
  2466. image if there is one. See ``help(colormaps)`` for more information.
  2467. """
  2468. set_cmap("hsv")
  2469. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2470. def jet():
  2471. """
  2472. Set the colormap to "jet".
  2473. This changes the default colormap as well as the colormap of the current
  2474. image if there is one. See ``help(colormaps)`` for more information.
  2475. """
  2476. set_cmap("jet")
  2477. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2478. def pink():
  2479. """
  2480. Set the colormap to "pink".
  2481. This changes the default colormap as well as the colormap of the current
  2482. image if there is one. See ``help(colormaps)`` for more information.
  2483. """
  2484. set_cmap("pink")
  2485. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2486. def prism():
  2487. """
  2488. Set the colormap to "prism".
  2489. This changes the default colormap as well as the colormap of the current
  2490. image if there is one. See ``help(colormaps)`` for more information.
  2491. """
  2492. set_cmap("prism")
  2493. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2494. def spring():
  2495. """
  2496. Set the colormap to "spring".
  2497. This changes the default colormap as well as the colormap of the current
  2498. image if there is one. See ``help(colormaps)`` for more information.
  2499. """
  2500. set_cmap("spring")
  2501. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2502. def summer():
  2503. """
  2504. Set the colormap to "summer".
  2505. This changes the default colormap as well as the colormap of the current
  2506. image if there is one. See ``help(colormaps)`` for more information.
  2507. """
  2508. set_cmap("summer")
  2509. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2510. def winter():
  2511. """
  2512. Set the colormap to "winter".
  2513. This changes the default colormap as well as the colormap of the current
  2514. image if there is one. See ``help(colormaps)`` for more information.
  2515. """
  2516. set_cmap("winter")
  2517. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2518. def magma():
  2519. """
  2520. Set the colormap to "magma".
  2521. This changes the default colormap as well as the colormap of the current
  2522. image if there is one. See ``help(colormaps)`` for more information.
  2523. """
  2524. set_cmap("magma")
  2525. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2526. def inferno():
  2527. """
  2528. Set the colormap to "inferno".
  2529. This changes the default colormap as well as the colormap of the current
  2530. image if there is one. See ``help(colormaps)`` for more information.
  2531. """
  2532. set_cmap("inferno")
  2533. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2534. def plasma():
  2535. """
  2536. Set the colormap to "plasma".
  2537. This changes the default colormap as well as the colormap of the current
  2538. image if there is one. See ``help(colormaps)`` for more information.
  2539. """
  2540. set_cmap("plasma")
  2541. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2542. def viridis():
  2543. """
  2544. Set the colormap to "viridis".
  2545. This changes the default colormap as well as the colormap of the current
  2546. image if there is one. See ``help(colormaps)`` for more information.
  2547. """
  2548. set_cmap("viridis")
  2549. # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
  2550. def nipy_spectral():
  2551. """
  2552. Set the colormap to "nipy_spectral".
  2553. This changes the default colormap as well as the colormap of the current
  2554. image if there is one. See ``help(colormaps)`` for more information.
  2555. """
  2556. set_cmap("nipy_spectral")
  2557. _setup_pyplot_info_docstrings()