1
0

pyplot.py 108 KB

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