pyplot.py 113 KB

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