12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269 |
- # Note: The first part of this file can be modified in place, but the latter
- # part is autogenerated by the boilerplate.py script.
- """
- `matplotlib.pyplot` is a state-based interface to matplotlib. It provides
- a MATLAB-like way of plotting.
- pyplot is mainly intended for interactive plots and simple cases of
- programmatic plot generation::
- import numpy as np
- import matplotlib.pyplot as plt
- x = np.arange(0, 5, 0.1)
- y = np.sin(x)
- plt.plot(x, y)
- The object-oriented API is recommended for more complex plots.
- """
- import functools
- import importlib
- import inspect
- import logging
- from numbers import Number
- import re
- import sys
- import time
- from cycler import cycler
- import matplotlib
- import matplotlib.colorbar
- import matplotlib.image
- from matplotlib import rcsetup, style
- from matplotlib import _pylab_helpers, interactive
- from matplotlib import cbook
- from matplotlib.cbook import dedent, deprecated, silent_list, warn_deprecated
- from matplotlib import docstring
- from matplotlib.backend_bases import FigureCanvasBase
- from matplotlib.figure import Figure, figaspect
- from matplotlib.gridspec import GridSpec
- from matplotlib import rcParams, rcParamsDefault, get_backend, rcParamsOrig
- from matplotlib import rc_context
- from matplotlib.rcsetup import interactive_bk as _interactive_bk
- from matplotlib.artist import getp, get, Artist
- from matplotlib.artist import setp as _setp
- from matplotlib.axes import Axes, Subplot
- from matplotlib.projections import PolarAxes
- from matplotlib import mlab # for _csv2rec, detrend_none, window_hanning
- from matplotlib.scale import get_scale_docs, get_scale_names
- from matplotlib import cm
- from matplotlib.cm import get_cmap, register_cmap
- import numpy as np
- # We may not need the following imports here:
- from matplotlib.colors import Normalize
- from matplotlib.lines import Line2D
- from matplotlib.text import Text, Annotation
- from matplotlib.patches import Polygon, Rectangle, Circle, Arrow
- from matplotlib.widgets import SubplotTool, Button, Slider, Widget
- from .ticker import TickHelper, Formatter, FixedFormatter, NullFormatter,\
- FuncFormatter, FormatStrFormatter, ScalarFormatter,\
- LogFormatter, LogFormatterExponent, LogFormatterMathtext,\
- Locator, IndexLocator, FixedLocator, NullLocator,\
- LinearLocator, LogLocator, AutoLocator, MultipleLocator,\
- MaxNLocator
- from matplotlib.backends import _get_running_interactive_framework
- _log = logging.getLogger(__name__)
- ## Global ##
- _IP_REGISTERED = None
- _INSTALL_FIG_OBSERVER = False
- def install_repl_displayhook():
- """
- Install a repl display hook so that any stale figure are automatically
- redrawn when control is returned to the repl.
- This works both with IPython and with vanilla python shells.
- """
- global _IP_REGISTERED
- global _INSTALL_FIG_OBSERVER
- class _NotIPython(Exception):
- pass
- # see if we have IPython hooks around, if use them
- try:
- if 'IPython' in sys.modules:
- from IPython import get_ipython
- ip = get_ipython()
- if ip is None:
- raise _NotIPython()
- if _IP_REGISTERED:
- return
- def post_execute():
- if matplotlib.is_interactive():
- draw_all()
- # IPython >= 2
- try:
- ip.events.register('post_execute', post_execute)
- except AttributeError:
- # IPython 1.x
- ip.register_post_execute(post_execute)
- _IP_REGISTERED = post_execute
- _INSTALL_FIG_OBSERVER = False
- # trigger IPython's eventloop integration, if available
- from IPython.core.pylabtools import backend2gui
- ipython_gui_name = backend2gui.get(get_backend())
- if ipython_gui_name:
- ip.enable_gui(ipython_gui_name)
- else:
- _INSTALL_FIG_OBSERVER = True
- # import failed or ipython is not running
- except (ImportError, _NotIPython):
- _INSTALL_FIG_OBSERVER = True
- def uninstall_repl_displayhook():
- """
- Uninstall the matplotlib display hook.
- .. warning::
- Need IPython >= 2 for this to work. For IPython < 2 will raise a
- ``NotImplementedError``
- .. warning::
- If you are using vanilla python and have installed another
- display hook this will reset ``sys.displayhook`` to what ever
- function was there when matplotlib installed it's displayhook,
- possibly discarding your changes.
- """
- global _IP_REGISTERED
- global _INSTALL_FIG_OBSERVER
- if _IP_REGISTERED:
- from IPython import get_ipython
- ip = get_ipython()
- try:
- ip.events.unregister('post_execute', _IP_REGISTERED)
- except AttributeError:
- raise NotImplementedError("Can not unregister events "
- "in IPython < 2.0")
- _IP_REGISTERED = None
- if _INSTALL_FIG_OBSERVER:
- _INSTALL_FIG_OBSERVER = False
- draw_all = _pylab_helpers.Gcf.draw_all
- @functools.wraps(matplotlib.set_loglevel)
- def set_loglevel(*args, **kwargs): # Ensure this appears in the pyplot docs.
- return matplotlib.set_loglevel(*args, **kwargs)
- @docstring.copy(Artist.findobj)
- def findobj(o=None, match=None, include_self=True):
- if o is None:
- o = gcf()
- return o.findobj(match, include_self=include_self)
- def switch_backend(newbackend):
- """
- Close all open figures and set the Matplotlib backend.
- The argument is case-insensitive. Switching to an interactive backend is
- possible only if no event loop for another interactive backend has started.
- Switching to and from non-interactive backends is always possible.
- Parameters
- ----------
- newbackend : str
- The name of the backend to use.
- """
- close("all")
- if newbackend is rcsetup._auto_backend_sentinel:
- # Don't try to fallback on the cairo-based backends as they each have
- # an additional dependency (pycairo) over the agg-based backend, and
- # are of worse quality.
- for candidate in [
- "macosx", "qt5agg", "qt4agg", "gtk3agg", "tkagg", "wxagg"]:
- try:
- switch_backend(candidate)
- except ImportError:
- continue
- else:
- rcParamsOrig['backend'] = candidate
- return
- else:
- # Switching to Agg should always succeed; if it doesn't, let the
- # exception propagate out.
- switch_backend("agg")
- rcParamsOrig["backend"] = "agg"
- return
- backend_name = (
- newbackend[9:] if newbackend.startswith("module://")
- else "matplotlib.backends.backend_{}".format(newbackend.lower()))
- backend_mod = importlib.import_module(backend_name)
- Backend = type(
- "Backend", (matplotlib.backends._Backend,), vars(backend_mod))
- _log.debug("Loaded backend %s version %s.",
- newbackend, Backend.backend_version)
- required_framework = getattr(
- Backend.FigureCanvas, "required_interactive_framework", None)
- if required_framework is not None:
- current_framework = \
- matplotlib.backends._get_running_interactive_framework()
- if (current_framework and required_framework
- and current_framework != required_framework):
- raise ImportError(
- "Cannot load backend {!r} which requires the {!r} interactive "
- "framework, as {!r} is currently running".format(
- newbackend, required_framework, current_framework))
- rcParams['backend'] = rcParamsDefault['backend'] = newbackend
- global _backend_mod, new_figure_manager, draw_if_interactive, _show
- _backend_mod = backend_mod
- new_figure_manager = Backend.new_figure_manager
- draw_if_interactive = Backend.draw_if_interactive
- _show = Backend.show
- # Need to keep a global reference to the backend for compatibility reasons.
- # See https://github.com/matplotlib/matplotlib/issues/6092
- matplotlib.backends.backend = newbackend
- def show(*args, **kw):
- """
- Display all figures.
- When running in ipython with its pylab mode, display all
- figures and return to the ipython prompt.
- In non-interactive mode, display all figures and block until
- the figures have been closed; in interactive mode it has no
- effect unless figures were created prior to a change from
- non-interactive to interactive mode (not recommended). In
- that case it displays the figures but does not block.
- Parameters
- ----------
- block : bool, optional
- This is experimental, and may be set to ``True`` or ``False`` to
- override the blocking behavior described above.
- """
- global _show
- return _show(*args, **kw)
- def isinteractive():
- """Return whether to redraw after every plotting command."""
- return matplotlib.is_interactive()
- def ioff():
- """Turn the interactive mode off."""
- matplotlib.interactive(False)
- uninstall_repl_displayhook()
- def ion():
- """Turn the interactive mode on."""
- matplotlib.interactive(True)
- install_repl_displayhook()
- def pause(interval):
- """
- Pause for *interval* seconds.
- If there is an active figure, it will be updated and displayed before the
- pause, and the GUI event loop (if any) will run during the pause.
- This can be used for crude animation. For more complex animation, see
- :mod:`matplotlib.animation`.
- Notes
- -----
- This function is experimental; its behavior may be changed or extended in a
- future release.
- """
- manager = _pylab_helpers.Gcf.get_active()
- if manager is not None:
- canvas = manager.canvas
- if canvas.figure.stale:
- canvas.draw_idle()
- show(block=False)
- canvas.start_event_loop(interval)
- else:
- time.sleep(interval)
- @docstring.copy(matplotlib.rc)
- def rc(group, **kwargs):
- matplotlib.rc(group, **kwargs)
- @docstring.copy(matplotlib.rc_context)
- def rc_context(rc=None, fname=None):
- return matplotlib.rc_context(rc, fname)
- @docstring.copy(matplotlib.rcdefaults)
- def rcdefaults():
- matplotlib.rcdefaults()
- if matplotlib.is_interactive():
- draw_all()
- ## Current image ##
- def gci():
- """
- Get the current colorable artist.
- Specifically, returns the current `.ScalarMappable` instance (`.Image`
- created by `imshow` or `figimage`, `.Collection` created by `pcolor` or
- `scatter`, etc.), or *None* if no such instance has been defined.
- The current image is an attribute of the current axes, or the nearest
- earlier axes in the current figure that contains an image.
- Notes
- -----
- Historically, the only colorable artists were images; hence the name
- ``gci`` (get current image).
- """
- return gcf()._gci()
- ## Any Artist ##
- # (getp is simply imported)
- @docstring.copy(_setp)
- def setp(obj, *args, **kwargs):
- return _setp(obj, *args, **kwargs)
- def xkcd(scale=1, length=100, randomness=2):
- """
- Turn on `xkcd <https://xkcd.com/>`_ sketch-style drawing mode.
- This will only have effect on things drawn after this function is
- called.
- For best results, the "Humor Sans" font should be installed: it is
- not included with matplotlib.
- Parameters
- ----------
- scale : float, optional
- The amplitude of the wiggle perpendicular to the source line.
- length : float, optional
- The length of the wiggle along the line.
- randomness : float, optional
- The scale factor by which the length is shrunken or expanded.
- Notes
- -----
- This function works by a number of rcParams, so it will probably
- override others you have set before.
- If you want the effects of this function to be temporary, it can
- be used as a context manager, for example::
- with plt.xkcd():
- # This figure will be in XKCD-style
- fig1 = plt.figure()
- # ...
- # This figure will be in regular style
- fig2 = plt.figure()
- """
- if rcParams['text.usetex']:
- raise RuntimeError(
- "xkcd mode is not compatible with text.usetex = True")
- from matplotlib import patheffects
- return rc_context({
- 'font.family': ['xkcd', 'xkcd Script', 'Humor Sans', 'Comic Neue',
- 'Comic Sans MS'],
- 'font.size': 14.0,
- 'path.sketch': (scale, length, randomness),
- 'path.effects': [patheffects.withStroke(linewidth=4, foreground="w")],
- 'axes.linewidth': 1.5,
- 'lines.linewidth': 2.0,
- 'figure.facecolor': 'white',
- 'grid.linewidth': 0.0,
- 'axes.grid': False,
- 'axes.unicode_minus': False,
- 'axes.edgecolor': 'black',
- 'xtick.major.size': 8,
- 'xtick.major.width': 3,
- 'ytick.major.size': 8,
- 'ytick.major.width': 3,
- })
- ## Figures ##
- def figure(num=None, # autoincrement if None, else integer from 1-N
- figsize=None, # defaults to rc figure.figsize
- dpi=None, # defaults to rc figure.dpi
- facecolor=None, # defaults to rc figure.facecolor
- edgecolor=None, # defaults to rc figure.edgecolor
- frameon=True,
- FigureClass=Figure,
- clear=False,
- **kwargs
- ):
- """
- Create a new figure.
- Parameters
- ----------
- num : int or str, optional, default: None
- If not provided, a new figure will be created, and the figure number
- will be incremented. The figure objects holds this number in a `number`
- attribute.
- If num is provided, and a figure with this id already exists, make
- it active, and returns a reference to it. If this figure does not
- exists, create it and returns it.
- If num is a string, the window title will be set to this figure's
- *num*.
- figsize : (float, float), optional, default: None
- width, height in inches. If not provided, defaults to
- :rc:`figure.figsize` = ``[6.4, 4.8]``.
- dpi : integer, optional, default: None
- resolution of the figure. If not provided, defaults to
- :rc:`figure.dpi` = ``100``.
- facecolor : color
- the background color. If not provided, defaults to
- :rc:`figure.facecolor` = ``'w'``.
- edgecolor : color
- the border color. If not provided, defaults to
- :rc:`figure.edgecolor` = ``'w'``.
- frameon : bool, optional, default: True
- If False, suppress drawing the figure frame.
- FigureClass : subclass of `~matplotlib.figure.Figure`
- Optionally use a custom `.Figure` instance.
- clear : bool, optional, default: False
- If True and the figure already exists, then it is cleared.
- Returns
- -------
- figure : `~matplotlib.figure.Figure`
- The `.Figure` instance returned will also be passed to
- new_figure_manager in the backends, which allows to hook custom
- `.Figure` classes into the pyplot interface. Additional kwargs will be
- passed to the `.Figure` init function.
- Notes
- -----
- If you are creating many figures, make sure you explicitly call
- `.pyplot.close` on the figures you are not using, because this will
- enable pyplot to properly clean up the memory.
- `~matplotlib.rcParams` defines the default values, which can be modified
- in the matplotlibrc file.
- """
- if figsize is None:
- figsize = rcParams['figure.figsize']
- if dpi is None:
- dpi = rcParams['figure.dpi']
- if facecolor is None:
- facecolor = rcParams['figure.facecolor']
- if edgecolor is None:
- edgecolor = rcParams['figure.edgecolor']
- allnums = get_fignums()
- next_num = max(allnums) + 1 if allnums else 1
- figLabel = ''
- if num is None:
- num = next_num
- elif isinstance(num, str):
- figLabel = num
- allLabels = get_figlabels()
- if figLabel not in allLabels:
- if figLabel == 'all':
- cbook._warn_external(
- "close('all') closes all existing figures")
- num = next_num
- else:
- inum = allLabels.index(figLabel)
- num = allnums[inum]
- else:
- num = int(num) # crude validation of num argument
- figManager = _pylab_helpers.Gcf.get_fig_manager(num)
- if figManager is None:
- max_open_warning = rcParams['figure.max_open_warning']
- if len(allnums) >= max_open_warning >= 1:
- cbook._warn_external(
- "More than %d figures have been opened. Figures "
- "created through the pyplot interface "
- "(`matplotlib.pyplot.figure`) are retained until "
- "explicitly closed and may consume too much memory. "
- "(To control this warning, see the rcParam "
- "`figure.max_open_warning`)." %
- max_open_warning, RuntimeWarning)
- if get_backend().lower() == 'ps':
- dpi = 72
- figManager = new_figure_manager(num, figsize=figsize,
- dpi=dpi,
- facecolor=facecolor,
- edgecolor=edgecolor,
- frameon=frameon,
- FigureClass=FigureClass,
- **kwargs)
- if figLabel:
- figManager.set_window_title(figLabel)
- figManager.canvas.figure.set_label(figLabel)
- # make this figure current on button press event
- def make_active(event):
- _pylab_helpers.Gcf.set_active(figManager)
- cid = figManager.canvas.mpl_connect('button_press_event', make_active)
- figManager._cidgcf = cid
- _pylab_helpers.Gcf.set_active(figManager)
- fig = figManager.canvas.figure
- fig.number = num
- # make sure backends (inline) that we don't ship that expect this
- # to be called in plotting commands to make the figure call show
- # still work. There is probably a better way to do this in the
- # FigureManager base class.
- if matplotlib.is_interactive():
- draw_if_interactive()
- if _INSTALL_FIG_OBSERVER:
- fig.stale_callback = _auto_draw_if_interactive
- if clear:
- figManager.canvas.figure.clear()
- return figManager.canvas.figure
- def _auto_draw_if_interactive(fig, val):
- """
- This is an internal helper function for making sure that auto-redrawing
- works as intended in the plain python repl.
- Parameters
- ----------
- fig : Figure
- A figure object which is assumed to be associated with a canvas
- """
- if (val and matplotlib.is_interactive()
- and not fig.canvas.is_saving()
- and not fig.canvas._is_idle_drawing):
- # Some artists can mark themselves as stale in the middle of drawing
- # (e.g. axes position & tick labels being computed at draw time), but
- # this shouldn't trigger a redraw because the current redraw will
- # already take them into account.
- with fig.canvas._idle_draw_cntx():
- fig.canvas.draw_idle()
- def gcf():
- """
- Get the current figure.
- If no current figure exists, a new one is created using
- `~.pyplot.figure()`.
- """
- figManager = _pylab_helpers.Gcf.get_active()
- if figManager is not None:
- return figManager.canvas.figure
- else:
- return figure()
- def fignum_exists(num):
- """Return whether the figure with the given id exists."""
- return _pylab_helpers.Gcf.has_fignum(num) or num in get_figlabels()
- def get_fignums():
- """Return a list of existing figure numbers."""
- return sorted(_pylab_helpers.Gcf.figs)
- def get_figlabels():
- """Return a list of existing figure labels."""
- figManagers = _pylab_helpers.Gcf.get_all_fig_managers()
- figManagers.sort(key=lambda m: m.num)
- return [m.canvas.figure.get_label() for m in figManagers]
- def get_current_fig_manager():
- """
- Return the figure manager of the current figure.
- The figure manager is a container for the actual backend-depended window
- that displays the figure on screen.
- If if no current figure exists, a new one is created an its figure
- manager is returned.
- Returns
- -------
- manager : `.FigureManagerBase` or backend-dependent subclass thereof
- """
- return gcf().canvas.manager
- @docstring.copy(FigureCanvasBase.mpl_connect)
- def connect(s, func):
- return gcf().canvas.mpl_connect(s, func)
- @docstring.copy(FigureCanvasBase.mpl_disconnect)
- def disconnect(cid):
- return gcf().canvas.mpl_disconnect(cid)
- def close(fig=None):
- """
- Close a figure window.
- Parameters
- ----------
- fig : None or int or str or `.Figure`
- The figure to close. There are a number of ways to specify this:
- - *None*: the current figure
- - `.Figure`: the given `.Figure` instance
- - ``int``: a figure number
- - ``str``: a figure name
- - 'all': all figures
- """
- if fig is None:
- figManager = _pylab_helpers.Gcf.get_active()
- if figManager is None:
- return
- else:
- _pylab_helpers.Gcf.destroy(figManager.num)
- elif fig == 'all':
- _pylab_helpers.Gcf.destroy_all()
- elif isinstance(fig, int):
- _pylab_helpers.Gcf.destroy(fig)
- elif hasattr(fig, 'int'):
- # if we are dealing with a type UUID, we
- # can use its integer representation
- _pylab_helpers.Gcf.destroy(fig.int)
- elif isinstance(fig, str):
- allLabels = get_figlabels()
- if fig in allLabels:
- num = get_fignums()[allLabels.index(fig)]
- _pylab_helpers.Gcf.destroy(num)
- elif isinstance(fig, Figure):
- _pylab_helpers.Gcf.destroy_fig(fig)
- else:
- raise TypeError("close() argument must be a Figure, an int, a string, "
- "or None, not '%s'")
- def clf():
- """Clear the current figure."""
- gcf().clf()
- def draw():
- """
- Redraw the current figure.
- This is used to update a figure that has been altered, but not
- automatically re-drawn. If interactive mode is on (via `.ion()`), this
- should be only rarely needed, but there may be ways to modify the state of
- a figure without marking it as "stale". Please report these cases as bugs.
- This is equivalent to calling ``fig.canvas.draw_idle()``, where ``fig`` is
- the current figure.
- """
- gcf().canvas.draw_idle()
- @docstring.copy(Figure.savefig)
- def savefig(*args, **kwargs):
- fig = gcf()
- res = fig.savefig(*args, **kwargs)
- fig.canvas.draw_idle() # need this if 'transparent=True' to reset colors
- return res
- ## Putting things in figures ##
- def figlegend(*args, **kwargs):
- return gcf().legend(*args, **kwargs)
- if Figure.legend.__doc__:
- figlegend.__doc__ = Figure.legend.__doc__.replace("legend(", "figlegend(")
- ## Axes ##
- @docstring.dedent_interpd
- def axes(arg=None, **kwargs):
- """
- Add an axes to the current figure and make it the current axes.
- Call signatures::
- plt.axes()
- plt.axes(rect, projection=None, polar=False, **kwargs)
- plt.axes(ax)
- Parameters
- ----------
- arg : None or 4-tuple
- The exact behavior of this function depends on the type:
- - *None*: A new full window axes is added using
- ``subplot(111, **kwargs)``
- - 4-tuple of floats *rect* = ``[left, bottom, width, height]``.
- A new axes is added with dimensions *rect* in normalized
- (0, 1) units using `~.Figure.add_axes` on the current figure.
- projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \
- 'polar', 'rectilinear', str}, optional
- The projection type of the `~.axes.Axes`. *str* is the name of
- a custom projection, see `~matplotlib.projections`. The default
- None results in a 'rectilinear' projection.
- polar : boolean, optional
- If True, equivalent to projection='polar'.
- sharex, sharey : `~.axes.Axes`, optional
- Share the x or y `~matplotlib.axis` with sharex and/or sharey.
- The axis will have the same limits, ticks, and scale as the axis
- of the shared axes.
- label : str
- A label for the returned axes.
- Other Parameters
- ----------------
- **kwargs
- This method also takes the keyword arguments for
- the returned axes class. The keyword arguments for the
- rectilinear axes class `~.axes.Axes` can be found in
- the following table but there might also be other keyword
- arguments if another projection is used, see the actual axes
- class.
- %(Axes)s
- Returns
- -------
- axes : `~.axes.Axes` (or a subclass of `~.axes.Axes`)
- The returned axes class depends on the projection used. It is
- `~.axes.Axes` if rectilinear projection are used and
- `.projections.polar.PolarAxes` if polar projection
- are used.
- Notes
- -----
- If the figure already has a axes with key (*args*,
- *kwargs*) then it will simply make that axes current and
- return it. This behavior is deprecated. Meanwhile, if you do
- not want this behavior (i.e., you want to force the creation of a
- new axes), you must use a unique set of args and kwargs. The axes
- *label* attribute has been exposed for this purpose: if you want
- two axes that are otherwise identical to be added to the figure,
- make sure you give them unique labels.
- See Also
- --------
- .Figure.add_axes
- .pyplot.subplot
- .Figure.add_subplot
- .Figure.subplots
- .pyplot.subplots
- Examples
- --------
- ::
- # Creating a new full window axes
- plt.axes()
- # Creating a new axes with specified dimensions and some kwargs
- plt.axes((left, bottom, width, height), facecolor='w')
- """
- if arg is None:
- return subplot(111, **kwargs)
- else:
- return gcf().add_axes(arg, **kwargs)
- def delaxes(ax=None):
- """
- Remove the `Axes` *ax* (defaulting to the current axes) from its figure.
- A KeyError is raised if the axes doesn't exist.
- """
- if ax is None:
- ax = gca()
- ax.figure.delaxes(ax)
- def sca(ax):
- """
- Set the current Axes instance to *ax*.
- The current Figure is updated to the parent of *ax*.
- """
- managers = _pylab_helpers.Gcf.get_all_fig_managers()
- for m in managers:
- if ax in m.canvas.figure.axes:
- _pylab_helpers.Gcf.set_active(m)
- m.canvas.figure.sca(ax)
- return
- raise ValueError("Axes instance argument was not found in a figure")
- def gca(**kwargs):
- """
- Get the current :class:`~matplotlib.axes.Axes` instance on the
- current figure matching the given keyword args, or create one.
- Examples
- --------
- To get the current polar axes on the current figure::
- plt.gca(projection='polar')
- If the current axes doesn't exist, or isn't a polar one, the appropriate
- axes will be created and then returned.
- See Also
- --------
- matplotlib.figure.Figure.gca : The figure's gca method.
- """
- return gcf().gca(**kwargs)
- ## More ways of creating axes ##
- @docstring.dedent_interpd
- def subplot(*args, **kwargs):
- """
- Add a subplot to the current figure.
- Wrapper of `.Figure.add_subplot` with a difference in behavior
- explained in the notes section.
- Call signatures::
- subplot(nrows, ncols, index, **kwargs)
- subplot(pos, **kwargs)
- subplot(ax)
- Parameters
- ----------
- *args
- Either a 3-digit integer or three separate integers
- describing the position of the subplot. If the three
- integers are *nrows*, *ncols*, and *index* in order, the
- subplot will take the *index* position on a grid with *nrows*
- rows and *ncols* columns. *index* starts at 1 in the upper left
- corner and increases to the right.
- *pos* is a three digit integer, where the first digit is the
- number of rows, the second the number of columns, and the third
- the index of the subplot. i.e. fig.add_subplot(235) is the same as
- fig.add_subplot(2, 3, 5). Note that all integers must be less than
- 10 for this form to work.
- projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \
- 'polar', 'rectilinear', str}, optional
- The projection type of the subplot (`~.axes.Axes`). *str* is the name
- of a custom projection, see `~matplotlib.projections`. The default
- None results in a 'rectilinear' projection.
- polar : boolean, optional
- If True, equivalent to projection='polar'.
- sharex, sharey : `~.axes.Axes`, optional
- Share the x or y `~matplotlib.axis` with sharex and/or sharey. The
- axis will have the same limits, ticks, and scale as the axis of the
- shared axes.
- label : str
- A label for the returned axes.
- Other Parameters
- ----------------
- **kwargs
- This method also takes the keyword arguments for the returned axes
- base class; except for the *figure* argument. The keyword arguments
- for the rectilinear base class `~.axes.Axes` can be found in
- the following table but there might also be other keyword
- arguments if another projection is used.
- %(Axes)s
- Returns
- -------
- axes : an `.axes.SubplotBase` subclass of `~.axes.Axes` (or a subclass \
- of `~.axes.Axes`)
- The axes of the subplot. The returned axes base class depends on
- the projection used. It is `~.axes.Axes` if rectilinear projection
- are used and `.projections.polar.PolarAxes` if polar projection
- are used. The returned axes is then a subplot subclass of the
- base class.
- Notes
- -----
- Creating a subplot will delete any pre-existing subplot that overlaps
- with it beyond sharing a boundary::
- import matplotlib.pyplot as plt
- # plot a line, implicitly creating a subplot(111)
- plt.plot([1, 2, 3])
- # now create a subplot which represents the top plot of a grid
- # with 2 rows and 1 column. Since this subplot will overlap the
- # first, the plot (and its axes) previously created, will be removed
- plt.subplot(211)
- If you do not want this behavior, use the `.Figure.add_subplot` method
- or the `.pyplot.axes` function instead.
- If the figure already has a subplot with key (*args*,
- *kwargs*) then it will simply make that subplot current and
- return it. This behavior is deprecated. Meanwhile, if you do
- not want this behavior (i.e., you want to force the creation of a
- new subplot), you must use a unique set of args and kwargs. The axes
- *label* attribute has been exposed for this purpose: if you want
- two subplots that are otherwise identical to be added to the figure,
- make sure you give them unique labels.
- In rare circumstances, `.add_subplot` may be called with a single
- argument, a subplot axes instance already created in the
- present figure but not in the figure's list of axes.
- See Also
- --------
- .Figure.add_subplot
- .pyplot.subplots
- .pyplot.axes
- .Figure.subplots
- Examples
- --------
- ::
- plt.subplot(221)
- # equivalent but more general
- ax1=plt.subplot(2, 2, 1)
- # add a subplot with no frame
- ax2=plt.subplot(222, frameon=False)
- # add a polar subplot
- plt.subplot(223, projection='polar')
- # add a red subplot that shares the x-axis with ax1
- plt.subplot(224, sharex=ax1, facecolor='red')
- # delete ax2 from the figure
- plt.delaxes(ax2)
- # add ax2 to the figure again
- plt.subplot(ax2)
- """
- # if subplot called without arguments, create subplot(1, 1, 1)
- if len(args) == 0:
- args = (1, 1, 1)
- # This check was added because it is very easy to type
- # subplot(1, 2, False) when subplots(1, 2, False) was intended
- # (sharex=False, that is). In most cases, no error will
- # ever occur, but mysterious behavior can result because what was
- # intended to be the sharex argument is instead treated as a
- # subplot index for subplot()
- if len(args) >= 3 and isinstance(args[2], bool):
- cbook._warn_external("The subplot index argument to subplot() appears "
- "to be a boolean. Did you intend to use "
- "subplots()?")
- fig = gcf()
- a = fig.add_subplot(*args, **kwargs)
- bbox = a.bbox
- byebye = []
- for other in fig.axes:
- if other == a:
- continue
- if bbox.fully_overlaps(other.bbox):
- byebye.append(other)
- for ax in byebye:
- delaxes(ax)
- return a
- def subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True,
- subplot_kw=None, gridspec_kw=None, **fig_kw):
- """
- Create a figure and a set of subplots.
- This utility wrapper makes it convenient to create common layouts of
- subplots, including the enclosing figure object, in a single call.
- Parameters
- ----------
- nrows, ncols : int, optional, default: 1
- Number of rows/columns of the subplot grid.
- sharex, sharey : bool or {'none', 'all', 'row', 'col'}, default: False
- Controls sharing of properties among x (`sharex`) or y (`sharey`)
- axes:
- - True or 'all': x- or y-axis will be shared among all subplots.
- - False or 'none': each subplot x- or y-axis will be independent.
- - 'row': each subplot row will share an x- or y-axis.
- - 'col': each subplot column will share an x- or y-axis.
- When subplots have a shared x-axis along a column, only the x tick
- labels of the bottom subplot are created. Similarly, when subplots
- have a shared y-axis along a row, only the y tick labels of the first
- column subplot are created. To later turn other subplots' ticklabels
- on, use `~matplotlib.axes.Axes.tick_params`.
- squeeze : bool, optional, default: True
- - If True, extra dimensions are squeezed out from the returned
- array of `~matplotlib.axes.Axes`:
- - if only one subplot is constructed (nrows=ncols=1), the
- resulting single Axes object is returned as a scalar.
- - for Nx1 or 1xM subplots, the returned object is a 1D numpy
- object array of Axes objects.
- - for NxM, subplots with N>1 and M>1 are returned as a 2D array.
- - If False, no squeezing at all is done: the returned Axes object is
- always a 2D array containing Axes instances, even if it ends up
- being 1x1.
- num : int or str, optional, default: None
- A `.pyplot.figure` keyword that sets the figure number or label.
- subplot_kw : dict, optional
- Dict with keywords passed to the
- `~matplotlib.figure.Figure.add_subplot` call used to create each
- subplot.
- gridspec_kw : dict, optional
- Dict with keywords passed to the `~matplotlib.gridspec.GridSpec`
- constructor used to create the grid the subplots are placed on.
- **fig_kw
- All additional keyword arguments are passed to the
- `.pyplot.figure` call.
- Returns
- -------
- fig : `~.figure.Figure`
- ax : `.axes.Axes` object or array of Axes objects.
- *ax* can be either a single `~matplotlib.axes.Axes` object or an
- array of Axes objects if more than one subplot was created. The
- dimensions of the resulting array can be controlled with the squeeze
- keyword, see above.
- Typical idioms for handling the return value are::
- # using the variable ax for single a Axes
- fig, ax = plt.subplots()
- # using the variable axs for multiple Axes
- fig, axs = plt.subplots(2, 2)
- # using tuple unpacking for multiple Axes
- fig, (ax1, ax2) = plt.subplot(1, 2)
- fig, ((ax1, ax2), (ax3, ax4)) = plt.subplot(2, 2)
- The names ``ax`` and pluralized ``axs`` are preferred over ``axes``
- because for the latter it's not clear if it refers to a single
- `~.axes.Axes` instance or a collection of these.
- Examples
- --------
- ::
- # First create some toy data:
- x = np.linspace(0, 2*np.pi, 400)
- y = np.sin(x**2)
- # Create just a figure and only one subplot
- fig, ax = plt.subplots()
- ax.plot(x, y)
- ax.set_title('Simple plot')
- # Create two subplots and unpack the output array immediately
- f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
- ax1.plot(x, y)
- ax1.set_title('Sharing Y axis')
- ax2.scatter(x, y)
- # Create four polar axes and access them through the returned array
- fig, axs = plt.subplots(2, 2, subplot_kw=dict(polar=True))
- axs[0, 0].plot(x, y)
- axs[1, 1].scatter(x, y)
- # Share a X axis with each column of subplots
- plt.subplots(2, 2, sharex='col')
- # Share a Y axis with each row of subplots
- plt.subplots(2, 2, sharey='row')
- # Share both X and Y axes with all subplots
- plt.subplots(2, 2, sharex='all', sharey='all')
- # Note that this is the same as
- plt.subplots(2, 2, sharex=True, sharey=True)
- # Create figure number 10 with a single subplot
- # and clears it if it already exists.
- fig, ax = plt.subplots(num=10, clear=True)
- See Also
- --------
- .pyplot.figure
- .pyplot.subplot
- .pyplot.axes
- .Figure.subplots
- .Figure.add_subplot
- """
- fig = figure(**fig_kw)
- axs = fig.subplots(nrows=nrows, ncols=ncols, sharex=sharex, sharey=sharey,
- squeeze=squeeze, subplot_kw=subplot_kw,
- gridspec_kw=gridspec_kw)
- return fig, axs
- def subplot2grid(shape, loc, rowspan=1, colspan=1, fig=None, **kwargs):
- """
- Create an axis at specific location inside a regular grid.
- Parameters
- ----------
- shape : sequence of 2 ints
- Shape of grid in which to place axis.
- First entry is number of rows, second entry is number of columns.
- loc : sequence of 2 ints
- Location to place axis within grid.
- First entry is row number, second entry is column number.
- rowspan : int
- Number of rows for the axis to span to the right.
- colspan : int
- Number of columns for the axis to span downwards.
- fig : `Figure`, optional
- Figure to place axis in. Defaults to current figure.
- **kwargs
- Additional keyword arguments are handed to `add_subplot`.
- Notes
- -----
- The following call ::
- subplot2grid(shape, loc, rowspan=1, colspan=1)
- is identical to ::
- gridspec=GridSpec(shape[0], shape[1])
- subplotspec=gridspec.new_subplotspec(loc, rowspan, colspan)
- subplot(subplotspec)
- """
- if fig is None:
- fig = gcf()
- s1, s2 = shape
- subplotspec = GridSpec(s1, s2).new_subplotspec(loc,
- rowspan=rowspan,
- colspan=colspan)
- a = fig.add_subplot(subplotspec, **kwargs)
- bbox = a.bbox
- byebye = []
- for other in fig.axes:
- if other == a:
- continue
- if bbox.fully_overlaps(other.bbox):
- byebye.append(other)
- for ax in byebye:
- delaxes(ax)
- return a
- def twinx(ax=None):
- """
- Make and return a second axes that shares the *x*-axis. The new axes will
- overlay *ax* (or the current axes if *ax* is *None*), and its ticks will be
- on the right.
- Examples
- --------
- :doc:`/gallery/subplots_axes_and_figures/two_scales`
- """
- if ax is None:
- ax = gca()
- ax1 = ax.twinx()
- return ax1
- def twiny(ax=None):
- """
- Make and return a second axes that shares the *y*-axis. The new axes will
- overlay *ax* (or the current axes if *ax* is *None*), and its ticks will be
- on the top.
- Examples
- --------
- :doc:`/gallery/subplots_axes_and_figures/two_scales`
- """
- if ax is None:
- ax = gca()
- ax1 = ax.twiny()
- return ax1
- def subplots_adjust(left=None, bottom=None, right=None, top=None,
- wspace=None, hspace=None):
- """
- Tune the subplot layout.
- The parameter meanings (and suggested defaults) are::
- left = 0.125 # the left side of the subplots of the figure
- right = 0.9 # the right side of the subplots of the figure
- bottom = 0.1 # the bottom of the subplots of the figure
- top = 0.9 # the top of the subplots of the figure
- wspace = 0.2 # the amount of width reserved for space between subplots,
- # expressed as a fraction of the average axis width
- hspace = 0.2 # the amount of height reserved for space between subplots,
- # expressed as a fraction of the average axis height
- The actual defaults are controlled by the rc file
- """
- fig = gcf()
- fig.subplots_adjust(left, bottom, right, top, wspace, hspace)
- def subplot_tool(targetfig=None):
- """
- Launch a subplot tool window for a figure.
- A :class:`matplotlib.widgets.SubplotTool` instance is returned.
- """
- if targetfig is None:
- targetfig = gcf()
- tbar = rcParams['toolbar'] # Turn off navigation toolbar for the toolfig.
- rcParams['toolbar'] = 'None'
- toolfig = figure(figsize=(6, 3))
- toolfig.subplots_adjust(top=0.9)
- rcParams['toolbar'] = tbar
- if hasattr(targetfig.canvas, "manager"): # Restore the current figure.
- _pylab_helpers.Gcf.set_active(targetfig.canvas.manager)
- return SubplotTool(targetfig, toolfig)
- def tight_layout(pad=1.08, h_pad=None, w_pad=None, rect=None):
- """
- Automatically adjust subplot parameters to give specified padding.
- Parameters
- ----------
- pad : float
- Padding between the figure edge and the edges of subplots,
- as a fraction of the font size.
- h_pad, w_pad : float, optional
- Padding (height/width) between edges of adjacent subplots,
- as a fraction of the font size. Defaults to *pad*.
- rect : tuple (left, bottom, right, top), optional
- A rectangle (left, bottom, right, top) in the normalized
- figure coordinate that the whole subplots area (including
- labels) will fit into. Default is (0, 0, 1, 1).
- """
- gcf().tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
- def box(on=None):
- """
- Turn the axes box on or off on the current axes.
- Parameters
- ----------
- on : bool or None
- The new `~matplotlib.axes.Axes` box state. If ``None``, toggle
- the state.
- See Also
- --------
- :meth:`matplotlib.axes.Axes.set_frame_on`
- :meth:`matplotlib.axes.Axes.get_frame_on`
- """
- ax = gca()
- if on is None:
- on = not ax.get_frame_on()
- ax.set_frame_on(on)
- ## Axis ##
- def xlim(*args, **kwargs):
- """
- Get or set the x limits of the current axes.
- Call signatures::
- left, right = xlim() # return the current xlim
- xlim((left, right)) # set the xlim to left, right
- xlim(left, right) # set the xlim to left, right
- If you do not specify args, you can pass *left* or *right* as kwargs,
- i.e.::
- xlim(right=3) # adjust the right leaving left unchanged
- xlim(left=1) # adjust the left leaving right unchanged
- Setting limits turns autoscaling off for the x-axis.
- Returns
- -------
- left, right
- A tuple of the new x-axis limits.
- Notes
- -----
- Calling this function with no arguments (e.g. ``xlim()``) is the pyplot
- equivalent of calling `~.Axes.get_xlim` on the current axes.
- Calling this function with arguments is the pyplot equivalent of calling
- `~.Axes.set_xlim` on the current axes. All arguments are passed though.
- """
- ax = gca()
- if not args and not kwargs:
- return ax.get_xlim()
- ret = ax.set_xlim(*args, **kwargs)
- return ret
- def ylim(*args, **kwargs):
- """
- Get or set the y-limits of the current axes.
- Call signatures::
- bottom, top = ylim() # return the current ylim
- ylim((bottom, top)) # set the ylim to bottom, top
- ylim(bottom, top) # set the ylim to bottom, top
- If you do not specify args, you can alternatively pass *bottom* or
- *top* as kwargs, i.e.::
- ylim(top=3) # adjust the top leaving bottom unchanged
- ylim(bottom=1) # adjust the bottom leaving top unchanged
- Setting limits turns autoscaling off for the y-axis.
- Returns
- -------
- bottom, top
- A tuple of the new y-axis limits.
- Notes
- -----
- Calling this function with no arguments (e.g. ``ylim()``) is the pyplot
- equivalent of calling `~.Axes.get_ylim` on the current axes.
- Calling this function with arguments is the pyplot equivalent of calling
- `~.Axes.set_ylim` on the current axes. All arguments are passed though.
- """
- ax = gca()
- if not args and not kwargs:
- return ax.get_ylim()
- ret = ax.set_ylim(*args, **kwargs)
- return ret
- def xticks(ticks=None, labels=None, **kwargs):
- """
- Get or set the current tick locations and labels of the x-axis.
- Pass no arguments to return the current values without modifying them.
- Parameters
- ----------
- ticks : array-like, optional
- The list of xtick locations. Passing an empty list removes all xticks.
- labels : array-like, optional
- The labels to place at the given *ticks* locations. This argument can
- only be passed if *ticks* is passed as well.
- **kwargs
- `.Text` properties can be used to control the appearance of the labels.
- Returns
- -------
- locs
- The list of xtick locations.
- labels
- The list of xlabel `.Text` objects.
- Notes
- -----
- Calling this function with no arguments (e.g. ``xticks()``) is the pyplot
- equivalent of calling `~.Axes.get_xticks` and `~.Axes.get_xticklabels` on
- the current axes.
- Calling this function with arguments is the pyplot equivalent of calling
- `~.Axes.set_xticks` and `~.Axes.set_xticklabels` on the current axes.
- Examples
- --------
- >>> locs, labels = xticks() # Get the current locations and labels.
- >>> xticks(np.arange(0, 1, step=0.2)) # Set label locations.
- >>> xticks(np.arange(3), ['Tom', 'Dick', 'Sue']) # Set text labels.
- >>> xticks([0, 1, 2], ['January', 'February', 'March'],
- ... rotation=20) # Set text labels and properties.
- >>> xticks([]) # Disable xticks.
- """
- ax = gca()
- if ticks is None and labels is None:
- locs = ax.get_xticks()
- labels = ax.get_xticklabels()
- elif labels is None:
- locs = ax.set_xticks(ticks)
- labels = ax.get_xticklabels()
- else:
- locs = ax.set_xticks(ticks)
- labels = ax.set_xticklabels(labels, **kwargs)
- for l in labels:
- l.update(kwargs)
- return locs, labels
- def yticks(ticks=None, labels=None, **kwargs):
- """
- Get or set the current tick locations and labels of the y-axis.
- Pass no arguments to return the current values without modifying them.
- Parameters
- ----------
- ticks : array-like, optional
- The list of xtick locations. Passing an empty list removes all xticks.
- labels : array-like, optional
- The labels to place at the given *ticks* locations. This argument can
- only be passed if *ticks* is passed as well.
- **kwargs
- `.Text` properties can be used to control the appearance of the labels.
- Returns
- -------
- locs
- The list of ytick locations.
- labels
- The list of ylabel `.Text` objects.
- Notes
- -----
- Calling this function with no arguments (e.g. ``yticks()``) is the pyplot
- equivalent of calling `~.Axes.get_yticks` and `~.Axes.get_yticklabels` on
- the current axes.
- Calling this function with arguments is the pyplot equivalent of calling
- `~.Axes.set_yticks` and `~.Axes.set_yticklabels` on the current axes.
- Examples
- --------
- >>> locs, labels = yticks() # Get the current locations and labels.
- >>> yticks(np.arange(0, 1, step=0.2)) # Set label locations.
- >>> yticks(np.arange(3), ['Tom', 'Dick', 'Sue']) # Set text labels.
- >>> yticks([0, 1, 2], ['January', 'February', 'March'],
- ... rotation=45) # Set text labels and properties.
- >>> yticks([]) # Disable yticks.
- """
- ax = gca()
- if ticks is None and labels is None:
- locs = ax.get_yticks()
- labels = ax.get_yticklabels()
- elif labels is None:
- locs = ax.set_yticks(ticks)
- labels = ax.get_yticklabels()
- else:
- locs = ax.set_yticks(ticks)
- labels = ax.set_yticklabels(labels, **kwargs)
- for l in labels:
- l.update(kwargs)
- return locs, labels
- def rgrids(*args, **kwargs):
- """
- Get or set the radial gridlines on the current polar plot.
- Call signatures::
- lines, labels = rgrids()
- lines, labels = rgrids(radii, labels=None, angle=22.5, fmt=None, **kwargs)
- When called with no arguments, `.rgrids` simply returns the tuple
- (*lines*, *labels*). When called with arguments, the labels will
- appear at the specified radial distances and angle.
- Parameters
- ----------
- radii : tuple with floats
- The radii for the radial gridlines
- labels : tuple with strings or None
- The labels to use at each radial gridline. The
- `matplotlib.ticker.ScalarFormatter` will be used if None.
- angle : float
- The angular position of the radius labels in degrees.
- fmt : str or None
- Format string used in `matplotlib.ticker.FormatStrFormatter`.
- For example '%f'.
- Returns
- -------
- lines, labels : list of `.lines.Line2D`, list of `.text.Text`
- *lines* are the radial gridlines and *labels* are the tick labels.
- Other Parameters
- ----------------
- **kwargs
- *kwargs* are optional `~.Text` properties for the labels.
- Examples
- --------
- ::
- # set the locations of the radial gridlines
- lines, labels = rgrids( (0.25, 0.5, 1.0) )
- # set the locations and labels of the radial gridlines
- lines, labels = rgrids( (0.25, 0.5, 1.0), ('Tom', 'Dick', 'Harry' ))
- See Also
- --------
- .pyplot.thetagrids
- .projections.polar.PolarAxes.set_rgrids
- .Axis.get_gridlines
- .Axis.get_ticklabels
- """
- ax = gca()
- if not isinstance(ax, PolarAxes):
- raise RuntimeError('rgrids only defined for polar axes')
- if len(args) == 0:
- lines = ax.yaxis.get_gridlines()
- labels = ax.yaxis.get_ticklabels()
- else:
- lines, labels = ax.set_rgrids(*args, **kwargs)
- return lines, labels
- def thetagrids(*args, **kwargs):
- """
- Get or set the theta gridlines on the current polar plot.
- Call signatures::
- lines, labels = thetagrids()
- lines, labels = thetagrids(angles, labels=None, fmt=None, **kwargs)
- When called with no arguments, `.thetagrids` simply returns the tuple
- (*lines*, *labels*). When called with arguments, the labels will
- appear at the specified angles.
- Parameters
- ----------
- angles : tuple with floats, degrees
- The angles of the theta gridlines.
- labels : tuple with strings or None
- The labels to use at each radial gridline. The
- `.projections.polar.ThetaFormatter` will be used if None.
- fmt : str or None
- Format string used in `matplotlib.ticker.FormatStrFormatter`.
- For example '%f'. Note that the angle in radians will be used.
- Returns
- -------
- lines, labels : list of `.lines.Line2D`, list of `.text.Text`
- *lines* are the theta gridlines and *labels* are the tick labels.
- Other Parameters
- ----------------
- **kwargs
- *kwargs* are optional `~.Text` properties for the labels.
- Examples
- --------
- ::
- # set the locations of the angular gridlines
- lines, labels = thetagrids(range(45, 360, 90))
- # set the locations and labels of the angular gridlines
- lines, labels = thetagrids(range(45, 360, 90), ('NE', 'NW', 'SW', 'SE'))
- See Also
- --------
- .pyplot.rgrids
- .projections.polar.PolarAxes.set_thetagrids
- .Axis.get_gridlines
- .Axis.get_ticklabels
- """
- ax = gca()
- if not isinstance(ax, PolarAxes):
- raise RuntimeError('thetagrids only defined for polar axes')
- if len(args) == 0:
- lines = ax.xaxis.get_ticklines()
- labels = ax.xaxis.get_ticklabels()
- else:
- lines, labels = ax.set_thetagrids(*args, **kwargs)
- return lines, labels
- ## Plotting Info ##
- def plotting():
- pass
- def get_plot_commands():
- """
- Get a sorted list of all of the plotting commands.
- """
- # This works by searching for all functions in this module and removing
- # a few hard-coded exclusions, as well as all of the colormap-setting
- # functions, and anything marked as private with a preceding underscore.
- exclude = {'colormaps', 'colors', 'connect', 'disconnect',
- 'get_plot_commands', 'get_current_fig_manager', 'ginput',
- 'plotting', 'waitforbuttonpress'}
- exclude |= set(colormaps())
- this_module = inspect.getmodule(get_plot_commands)
- return sorted(
- name for name, obj in globals().items()
- if not name.startswith('_') and name not in exclude
- and inspect.isfunction(obj)
- and inspect.getmodule(obj) is this_module)
- def colormaps():
- """
- Matplotlib provides a number of colormaps, and others can be added using
- :func:`~matplotlib.cm.register_cmap`. This function documents the built-in
- colormaps, and will also return a list of all registered colormaps if
- called.
- You can set the colormap for an image, pcolor, scatter, etc,
- using a keyword argument::
- imshow(X, cmap=cm.hot)
- or using the :func:`set_cmap` function::
- imshow(X)
- pyplot.set_cmap('hot')
- pyplot.set_cmap('jet')
- In interactive mode, :func:`set_cmap` will update the colormap post-hoc,
- allowing you to see which one works best for your data.
- All built-in colormaps can be reversed by appending ``_r``: For instance,
- ``gray_r`` is the reverse of ``gray``.
- There are several common color schemes used in visualization:
- Sequential schemes
- for unipolar data that progresses from low to high
- Diverging schemes
- for bipolar data that emphasizes positive or negative deviations from a
- central value
- Cyclic schemes
- for plotting values that wrap around at the endpoints, such as phase
- angle, wind direction, or time of day
- Qualitative schemes
- for nominal data that has no inherent ordering, where color is used
- only to distinguish categories
- Matplotlib ships with 4 perceptually uniform color maps which are
- the recommended color maps for sequential data:
- ========= ===================================================
- Colormap Description
- ========= ===================================================
- inferno perceptually uniform shades of black-red-yellow
- magma perceptually uniform shades of black-red-white
- plasma perceptually uniform shades of blue-red-yellow
- viridis perceptually uniform shades of blue-green-yellow
- ========= ===================================================
- The following colormaps are based on the `ColorBrewer
- <http://colorbrewer2.org>`_ color specifications and designs developed by
- Cynthia Brewer:
- ColorBrewer Diverging (luminance is highest at the midpoint, and
- decreases towards differently-colored endpoints):
- ======== ===================================
- Colormap Description
- ======== ===================================
- BrBG brown, white, blue-green
- PiYG pink, white, yellow-green
- PRGn purple, white, green
- PuOr orange, white, purple
- RdBu red, white, blue
- RdGy red, white, gray
- RdYlBu red, yellow, blue
- RdYlGn red, yellow, green
- Spectral red, orange, yellow, green, blue
- ======== ===================================
- ColorBrewer Sequential (luminance decreases monotonically):
- ======== ====================================
- Colormap Description
- ======== ====================================
- Blues white to dark blue
- BuGn white, light blue, dark green
- BuPu white, light blue, dark purple
- GnBu white, light green, dark blue
- Greens white to dark green
- Greys white to black (not linear)
- Oranges white, orange, dark brown
- OrRd white, orange, dark red
- PuBu white, light purple, dark blue
- PuBuGn white, light purple, dark green
- PuRd white, light purple, dark red
- Purples white to dark purple
- RdPu white, pink, dark purple
- Reds white to dark red
- YlGn light yellow, dark green
- YlGnBu light yellow, light green, dark blue
- YlOrBr light yellow, orange, dark brown
- YlOrRd light yellow, orange, dark red
- ======== ====================================
- ColorBrewer Qualitative:
- (For plotting nominal data, :class:`ListedColormap` is used,
- not :class:`LinearSegmentedColormap`. Different sets of colors are
- recommended for different numbers of categories.)
- * Accent
- * Dark2
- * Paired
- * Pastel1
- * Pastel2
- * Set1
- * Set2
- * Set3
- A set of colormaps derived from those of the same name provided
- with Matlab are also included:
- ========= =======================================================
- Colormap Description
- ========= =======================================================
- autumn sequential linearly-increasing shades of red-orange-yellow
- bone sequential increasing black-white color map with
- a tinge of blue, to emulate X-ray film
- cool linearly-decreasing shades of cyan-magenta
- copper sequential increasing shades of black-copper
- flag repetitive red-white-blue-black pattern (not cyclic at
- endpoints)
- gray sequential linearly-increasing black-to-white
- grayscale
- hot sequential black-red-yellow-white, to emulate blackbody
- radiation from an object at increasing temperatures
- jet a spectral map with dark endpoints, blue-cyan-yellow-red;
- based on a fluid-jet simulation by NCSA [#]_
- pink sequential increasing pastel black-pink-white, meant
- for sepia tone colorization of photographs
- prism repetitive red-yellow-green-blue-purple-...-green pattern
- (not cyclic at endpoints)
- spring linearly-increasing shades of magenta-yellow
- summer sequential linearly-increasing shades of green-yellow
- winter linearly-increasing shades of blue-green
- ========= =======================================================
- A set of palettes from the `Yorick scientific visualisation
- package <https://dhmunro.github.io/yorick-doc/>`_, an evolution of
- the GIST package, both by David H. Munro are included:
- ============ =======================================================
- Colormap Description
- ============ =======================================================
- gist_earth mapmaker's colors from dark blue deep ocean to green
- lowlands to brown highlands to white mountains
- gist_heat sequential increasing black-red-orange-white, to emulate
- blackbody radiation from an iron bar as it grows hotter
- gist_ncar pseudo-spectral black-blue-green-yellow-red-purple-white
- colormap from National Center for Atmospheric
- Research [#]_
- gist_rainbow runs through the colors in spectral order from red to
- violet at full saturation (like *hsv* but not cyclic)
- gist_stern "Stern special" color table from Interactive Data
- Language software
- ============ =======================================================
- A set of cyclic color maps:
- ================ =================================================
- Colormap Description
- ================ =================================================
- hsv red-yellow-green-cyan-blue-magenta-red, formed by
- changing the hue component in the HSV color space
- twilight perceptually uniform shades of
- white-blue-black-red-white
- twilight_shifted perceptually uniform shades of
- black-blue-white-red-black
- ================ =================================================
- Other miscellaneous schemes:
- ============= =======================================================
- Colormap Description
- ============= =======================================================
- afmhot sequential black-orange-yellow-white blackbody
- spectrum, commonly used in atomic force microscopy
- brg blue-red-green
- bwr diverging blue-white-red
- coolwarm diverging blue-gray-red, meant to avoid issues with 3D
- shading, color blindness, and ordering of colors [#]_
- CMRmap "Default colormaps on color images often reproduce to
- confusing grayscale images. The proposed colormap
- maintains an aesthetically pleasing color image that
- automatically reproduces to a monotonic grayscale with
- discrete, quantifiable saturation levels." [#]_
- cubehelix Unlike most other color schemes cubehelix was designed
- by D.A. Green to be monotonically increasing in terms
- of perceived brightness. Also, when printed on a black
- and white postscript printer, the scheme results in a
- greyscale with monotonically increasing brightness.
- This color scheme is named cubehelix because the (r, g, b)
- values produced can be visualised as a squashed helix
- around the diagonal in the (r, g, b) color cube.
- gnuplot gnuplot's traditional pm3d scheme
- (black-blue-red-yellow)
- gnuplot2 sequential color printable as gray
- (black-blue-violet-yellow-white)
- ocean green-blue-white
- rainbow spectral purple-blue-green-yellow-orange-red colormap
- with diverging luminance
- seismic diverging blue-white-red
- nipy_spectral black-purple-blue-green-yellow-red-white spectrum,
- originally from the Neuroimaging in Python project
- terrain mapmaker's colors, blue-green-yellow-brown-white,
- originally from IGOR Pro
- ============= =======================================================
- The following colormaps are redundant and may be removed in future
- versions. It's recommended to use the names in the descriptions
- instead, which produce identical output:
- ========= =======================================================
- Colormap Description
- ========= =======================================================
- gist_gray identical to *gray*
- gist_yarg identical to *gray_r*
- binary identical to *gray_r*
- ========= =======================================================
- .. rubric:: Footnotes
- .. [#] Rainbow colormaps, ``jet`` in particular, are considered a poor
- choice for scientific visualization by many researchers: `Rainbow Color
- Map (Still) Considered Harmful
- <http://ieeexplore.ieee.org/document/4118486/?arnumber=4118486>`_
- .. [#] Resembles "BkBlAqGrYeOrReViWh200" from NCAR Command
- Language. See `Color Table Gallery
- <https://www.ncl.ucar.edu/Document/Graphics/color_table_gallery.shtml>`_
- .. [#] See `Diverging Color Maps for Scientific Visualization
- <http://www.kennethmoreland.com/color-maps/>`_ by Kenneth Moreland.
- .. [#] See `A Color Map for Effective Black-and-White Rendering of
- Color-Scale Images
- <https://www.mathworks.com/matlabcentral/fileexchange/2662-cmrmap-m>`_
- by Carey Rappaport
- """
- return sorted(cm.cmap_d)
- def _setup_pyplot_info_docstrings():
- """
- Generates the plotting docstring.
- These must be done after the entire module is imported, so it is
- called from the end of this module, which is generated by
- boilerplate.py.
- """
- commands = get_plot_commands()
- first_sentence = re.compile(r"(?:\s*).+?\.(?:\s+|$)", flags=re.DOTALL)
- # Collect the first sentence of the docstring for all of the
- # plotting commands.
- rows = []
- max_name = len("Function")
- max_summary = len("Description")
- for name in commands:
- doc = globals()[name].__doc__
- summary = ''
- if doc is not None:
- match = first_sentence.match(doc)
- if match is not None:
- summary = inspect.cleandoc(match.group(0)).replace('\n', ' ')
- name = '`%s`' % name
- rows.append([name, summary])
- max_name = max(max_name, len(name))
- max_summary = max(max_summary, len(summary))
- separator = '=' * max_name + ' ' + '=' * max_summary
- lines = [
- separator,
- '{:{}} {:{}}'.format('Function', max_name, 'Description', max_summary),
- separator,
- ] + [
- '{:{}} {:{}}'.format(name, max_name, summary, max_summary)
- for name, summary in rows
- ] + [
- separator,
- ]
- plotting.__doc__ = '\n'.join(lines)
- ## Plotting part 1: manually generated functions and wrappers ##
- def colorbar(mappable=None, cax=None, ax=None, **kw):
- if mappable is None:
- mappable = gci()
- if mappable is None:
- raise RuntimeError('No mappable was found to use for colorbar '
- 'creation. First define a mappable such as '
- 'an image (with imshow) or a contour set ('
- 'with contourf).')
- if ax is None:
- ax = gca()
- ret = gcf().colorbar(mappable, cax=cax, ax=ax, **kw)
- return ret
- colorbar.__doc__ = matplotlib.colorbar.colorbar_doc
- def clim(vmin=None, vmax=None):
- """
- Set the color limits of the current image.
- If either *vmin* or *vmax* is None, the image min/max respectively
- will be used for color scaling.
- If you want to set the clim of multiple images, use
- `~.ScalarMappable.set_clim` on every image, for example::
- for im in gca().get_images():
- im.set_clim(0, 0.5)
- """
- im = gci()
- if im is None:
- raise RuntimeError('You must first define an image, e.g., with imshow')
- im.set_clim(vmin, vmax)
- def set_cmap(cmap):
- """
- Set the default colormap, and applies it to the current image if any.
- Parameters
- ----------
- cmap : `~matplotib.colors.Colormap` or str
- A colormap instance or the name of a registered colormap.
- See Also
- --------
- colormaps
- matplotlib.cm.register_cmap
- matplotlib.cm.get_cmap
- """
- cmap = cm.get_cmap(cmap)
- rc('image', cmap=cmap.name)
- im = gci()
- if im is not None:
- im.set_cmap(cmap)
- @docstring.copy(matplotlib.image.imread)
- def imread(fname, format=None):
- return matplotlib.image.imread(fname, format)
- @docstring.copy(matplotlib.image.imsave)
- def imsave(fname, arr, **kwargs):
- return matplotlib.image.imsave(fname, arr, **kwargs)
- def matshow(A, fignum=None, **kwargs):
- """
- Display an array as a matrix in a new figure window.
- The origin is set at the upper left hand corner and rows (first
- dimension of the array) are displayed horizontally. The aspect
- ratio of the figure window is that of the array, unless this would
- make an excessively short or narrow figure.
- Tick labels for the xaxis are placed on top.
- Parameters
- ----------
- A : array-like(M, N)
- The matrix to be displayed.
- fignum : None or int or False
- If *None*, create a new figure window with automatic numbering.
- If a nonzero integer, draw into the figure with the given number
- (create it if it does not exist).
- If 0, use the current axes (or create one if it does not exist).
- .. note::
- Because of how `.Axes.matshow` tries to set the figure aspect
- ratio to be the one of the array, strange things may happen if you
- reuse an existing figure.
- Returns
- -------
- image : `~matplotlib.image.AxesImage`
- Other Parameters
- ----------------
- **kwargs : `~matplotlib.axes.Axes.imshow` arguments
- """
- A = np.asanyarray(A)
- if fignum == 0:
- ax = gca()
- else:
- # Extract actual aspect ratio of array and make appropriately sized
- # figure.
- fig = figure(fignum, figsize=figaspect(A))
- ax = fig.add_axes([0.15, 0.09, 0.775, 0.775])
- im = ax.matshow(A, **kwargs)
- sci(im)
- return im
- def polar(*args, **kwargs):
- """
- Make a polar plot.
- call signature::
- polar(theta, r, **kwargs)
- Multiple *theta*, *r* arguments are supported, with format strings, as in
- `plot`.
- """
- # If an axis already exists, check if it has a polar projection
- if gcf().get_axes():
- if not isinstance(gca(), PolarAxes):
- cbook._warn_external('Trying to create polar plot on an axis '
- 'that does not have a polar projection.')
- ax = gca(polar=True)
- ret = ax.plot(*args, **kwargs)
- return ret
- @cbook.deprecated("3.1")
- def plotfile(fname, cols=(0,), plotfuncs=None,
- comments='#', skiprows=0, checkrows=5, delimiter=',',
- names=None, subplots=True, newfig=True, **kwargs):
- """
- Plot the data in a file.
- *cols* is a sequence of column identifiers to plot. An identifier
- is either an int or a string. If it is an int, it indicates the
- column number. If it is a string, it indicates the column header.
- matplotlib will make column headers lower case, replace spaces with
- underscores, and remove all illegal characters; so ``'Adj Close*'``
- will have name ``'adj_close'``.
- - If len(*cols*) == 1, only that column will be plotted on the *y* axis.
- - If len(*cols*) > 1, the first element will be an identifier for
- data for the *x* axis and the remaining elements will be the
- column indexes for multiple subplots if *subplots* is *True*
- (the default), or for lines in a single subplot if *subplots*
- is *False*.
- *plotfuncs*, if not *None*, is a dictionary mapping identifier to
- an :class:`~matplotlib.axes.Axes` plotting function as a string.
- Default is 'plot', other choices are 'semilogy', 'fill', 'bar',
- etc. You must use the same type of identifier in the *cols*
- vector as you use in the *plotfuncs* dictionary, e.g., integer
- column numbers in both or column names in both. If *subplots*
- is *False*, then including any function such as 'semilogy'
- that changes the axis scaling will set the scaling for all
- columns.
- - *comments*: the character used to indicate the start of a comment
- in the file, or *None* to switch off the removal of comments
- - *skiprows*: is the number of rows from the top to skip
- - *checkrows*: is the number of rows to check to validate the column
- data type. When set to zero all rows are validated.
- - *delimiter*: is the character(s) separating row items
- - *names*: if not None, is a list of header names. In this case, no
- header will be read from the file
- If *newfig* is *True*, the plot always will be made in a new figure;
- if *False*, it will be made in the current figure if one exists,
- else in a new figure.
- kwargs are passed on to plotting functions.
- Example usage::
- # plot the 2nd and 4th column against the 1st in two subplots
- plotfile(fname, (0, 1, 3))
- # plot using column names; specify an alternate plot type for volume
- plotfile(fname, ('date', 'volume', 'adj_close'),
- plotfuncs={'volume': 'semilogy'})
- Note: plotfile is intended as a convenience for quickly plotting
- data from flat files; it is not intended as an alternative
- interface to general plotting with pyplot or matplotlib.
- """
- if newfig:
- fig = figure()
- else:
- fig = gcf()
- if len(cols) < 1:
- raise ValueError('must have at least one column of data')
- if plotfuncs is None:
- plotfuncs = {}
- with cbook._suppress_matplotlib_deprecation_warning():
- r = mlab._csv2rec(fname, comments=comments, skiprows=skiprows,
- checkrows=checkrows, delimiter=delimiter,
- names=names)
- def getname_val(identifier):
- 'return the name and column data for identifier'
- if isinstance(identifier, str):
- return identifier, r[identifier]
- elif isinstance(identifier, Number):
- name = r.dtype.names[int(identifier)]
- return name, r[name]
- else:
- raise TypeError('identifier must be a string or integer')
- xname, x = getname_val(cols[0])
- ynamelist = []
- if len(cols) == 1:
- ax1 = fig.add_subplot(1, 1, 1)
- funcname = plotfuncs.get(cols[0], 'plot')
- func = getattr(ax1, funcname)
- func(x, **kwargs)
- ax1.set_ylabel(xname)
- else:
- N = len(cols)
- for i in range(1, N):
- if subplots:
- if i == 1:
- ax = ax1 = fig.add_subplot(N - 1, 1, i)
- else:
- ax = fig.add_subplot(N - 1, 1, i, sharex=ax1)
- elif i == 1:
- ax = fig.add_subplot(1, 1, 1)
- yname, y = getname_val(cols[i])
- ynamelist.append(yname)
- funcname = plotfuncs.get(cols[i], 'plot')
- func = getattr(ax, funcname)
- func(x, y, **kwargs)
- if subplots:
- ax.set_ylabel(yname)
- if ax.is_last_row():
- ax.set_xlabel(xname)
- else:
- ax.set_xlabel('')
- if not subplots:
- ax.legend(ynamelist)
- if xname == 'date':
- fig.autofmt_xdate()
- # If rcParams['backend_fallback'] is true, and an interactive backend is
- # requested, ignore rcParams['backend'] and force selection of a backend that
- # is compatible with the current running interactive framework.
- if (rcParams["backend_fallback"]
- and dict.__getitem__(rcParams, "backend") in (
- set(_interactive_bk) - {'WebAgg', 'nbAgg'})
- and _get_running_interactive_framework()):
- dict.__setitem__(rcParams, "backend", rcsetup._auto_backend_sentinel)
- # Set up the backend.
- switch_backend(rcParams["backend"])
- # Just to be safe. Interactive mode can be turned on without
- # calling `plt.ion()` so register it again here.
- # This is safe because multiple calls to `install_repl_displayhook`
- # are no-ops and the registered function respect `mpl.is_interactive()`
- # to determine if they should trigger a draw.
- install_repl_displayhook()
- ################# REMAINING CONTENT GENERATED BY boilerplate.py ##############
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Figure.figimage)
- def figimage(
- X, xo=0, yo=0, alpha=None, norm=None, cmap=None, vmin=None,
- vmax=None, origin=None, resize=False, **kwargs):
- return gcf().figimage(
- X, xo=xo, yo=yo, alpha=alpha, norm=norm, cmap=cmap, vmin=vmin,
- vmax=vmax, origin=origin, resize=resize, **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Figure.text)
- def figtext(
- x, y, s, fontdict=None,
- withdash=cbook.deprecation._deprecated_parameter, **kwargs):
- return gcf().text(
- x, y, s, fontdict=fontdict, withdash=withdash, **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Figure.ginput)
- def ginput(
- n=1, timeout=30, show_clicks=True, mouse_add=1, mouse_pop=3,
- mouse_stop=2):
- return gcf().ginput(
- n=n, timeout=timeout, show_clicks=show_clicks,
- mouse_add=mouse_add, mouse_pop=mouse_pop,
- mouse_stop=mouse_stop)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Figure.suptitle)
- def suptitle(t, **kwargs):
- return gcf().suptitle(t, **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Figure.waitforbuttonpress)
- def waitforbuttonpress(timeout=-1):
- return gcf().waitforbuttonpress(timeout=timeout)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.acorr)
- def acorr(x, *, data=None, **kwargs):
- return gca().acorr(
- x, **({"data": data} if data is not None else {}), **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.angle_spectrum)
- def angle_spectrum(
- x, Fs=None, Fc=None, window=None, pad_to=None, sides=None, *,
- data=None, **kwargs):
- return gca().angle_spectrum(
- x, Fs=Fs, Fc=Fc, window=window, pad_to=pad_to, sides=sides,
- **({"data": data} if data is not None else {}), **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.annotate)
- def annotate(s, xy, *args, **kwargs):
- return gca().annotate(s, xy, *args, **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.arrow)
- def arrow(x, y, dx, dy, **kwargs):
- return gca().arrow(x, y, dx, dy, **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.autoscale)
- def autoscale(enable=True, axis='both', tight=None):
- return gca().autoscale(enable=enable, axis=axis, tight=tight)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.axhline)
- def axhline(y=0, xmin=0, xmax=1, **kwargs):
- return gca().axhline(y=y, xmin=xmin, xmax=xmax, **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.axhspan)
- def axhspan(ymin, ymax, xmin=0, xmax=1, **kwargs):
- return gca().axhspan(ymin, ymax, xmin=xmin, xmax=xmax, **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.axis)
- def axis(*args, emit=True, **kwargs):
- return gca().axis(*args, emit=emit, **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.axvline)
- def axvline(x=0, ymin=0, ymax=1, **kwargs):
- return gca().axvline(x=x, ymin=ymin, ymax=ymax, **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.axvspan)
- def axvspan(xmin, xmax, ymin=0, ymax=1, **kwargs):
- return gca().axvspan(xmin, xmax, ymin=ymin, ymax=ymax, **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.bar)
- def bar(
- x, height, width=0.8, bottom=None, *, align='center',
- data=None, **kwargs):
- return gca().bar(
- x, height, width=width, bottom=bottom, align=align,
- **({"data": data} if data is not None else {}), **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.barbs)
- def barbs(*args, data=None, **kw):
- return gca().barbs(
- *args, **({"data": data} if data is not None else {}), **kw)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.barh)
- def barh(y, width, height=0.8, left=None, *, align='center', **kwargs):
- return gca().barh(
- y, width, height=height, left=left, align=align, **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.boxplot)
- def boxplot(
- x, notch=None, sym=None, vert=None, whis=None,
- positions=None, widths=None, patch_artist=None,
- bootstrap=None, usermedians=None, conf_intervals=None,
- meanline=None, showmeans=None, showcaps=None, showbox=None,
- showfliers=None, boxprops=None, labels=None, flierprops=None,
- medianprops=None, meanprops=None, capprops=None,
- whiskerprops=None, manage_ticks=True, autorange=False,
- zorder=None, *, data=None):
- return gca().boxplot(
- x, notch=notch, sym=sym, vert=vert, whis=whis,
- positions=positions, widths=widths, patch_artist=patch_artist,
- bootstrap=bootstrap, usermedians=usermedians,
- conf_intervals=conf_intervals, meanline=meanline,
- showmeans=showmeans, showcaps=showcaps, showbox=showbox,
- showfliers=showfliers, boxprops=boxprops, labels=labels,
- flierprops=flierprops, medianprops=medianprops,
- meanprops=meanprops, capprops=capprops,
- whiskerprops=whiskerprops, manage_ticks=manage_ticks,
- autorange=autorange, zorder=zorder, **({"data": data} if data
- is not None else {}))
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.broken_barh)
- def broken_barh(xranges, yrange, *, data=None, **kwargs):
- return gca().broken_barh(
- xranges, yrange, **({"data": data} if data is not None else
- {}), **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.cla)
- def cla():
- return gca().cla()
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.clabel)
- def clabel(CS, *args, **kwargs):
- return gca().clabel(CS, *args, **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.cohere)
- def cohere(
- x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
- window=mlab.window_hanning, noverlap=0, pad_to=None,
- sides='default', scale_by_freq=None, *, data=None, **kwargs):
- return gca().cohere(
- x, y, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, window=window,
- noverlap=noverlap, pad_to=pad_to, sides=sides,
- scale_by_freq=scale_by_freq, **({"data": data} if data is not
- None else {}), **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.contour)
- def contour(*args, data=None, **kwargs):
- __ret = gca().contour(
- *args, **({"data": data} if data is not None else {}),
- **kwargs)
- if __ret._A is not None: sci(__ret) # noqa
- return __ret
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.contourf)
- def contourf(*args, data=None, **kwargs):
- __ret = gca().contourf(
- *args, **({"data": data} if data is not None else {}),
- **kwargs)
- if __ret._A is not None: sci(__ret) # noqa
- return __ret
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.csd)
- def csd(
- x, y, NFFT=None, Fs=None, Fc=None, detrend=None, window=None,
- noverlap=None, pad_to=None, sides=None, scale_by_freq=None,
- return_line=None, *, data=None, **kwargs):
- return gca().csd(
- x, y, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, window=window,
- noverlap=noverlap, pad_to=pad_to, sides=sides,
- scale_by_freq=scale_by_freq, return_line=return_line,
- **({"data": data} if data is not None else {}), **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.errorbar)
- def errorbar(
- x, y, yerr=None, xerr=None, fmt='', ecolor=None,
- elinewidth=None, capsize=None, barsabove=False, lolims=False,
- uplims=False, xlolims=False, xuplims=False, errorevery=1,
- capthick=None, *, data=None, **kwargs):
- return gca().errorbar(
- x, y, yerr=yerr, xerr=xerr, fmt=fmt, ecolor=ecolor,
- elinewidth=elinewidth, capsize=capsize, barsabove=barsabove,
- lolims=lolims, uplims=uplims, xlolims=xlolims,
- xuplims=xuplims, errorevery=errorevery, capthick=capthick,
- **({"data": data} if data is not None else {}), **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.eventplot)
- def eventplot(
- positions, orientation='horizontal', lineoffsets=1,
- linelengths=1, linewidths=None, colors=None,
- linestyles='solid', *, data=None, **kwargs):
- return gca().eventplot(
- positions, orientation=orientation, lineoffsets=lineoffsets,
- linelengths=linelengths, linewidths=linewidths, colors=colors,
- linestyles=linestyles, **({"data": data} if data is not None
- else {}), **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.fill)
- def fill(*args, data=None, **kwargs):
- return gca().fill(
- *args, **({"data": data} if data is not None else {}),
- **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.fill_between)
- def fill_between(
- x, y1, y2=0, where=None, interpolate=False, step=None, *,
- data=None, **kwargs):
- return gca().fill_between(
- x, y1, y2=y2, where=where, interpolate=interpolate, step=step,
- **({"data": data} if data is not None else {}), **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.fill_betweenx)
- def fill_betweenx(
- y, x1, x2=0, where=None, step=None, interpolate=False, *,
- data=None, **kwargs):
- return gca().fill_betweenx(
- y, x1, x2=x2, where=where, step=step, interpolate=interpolate,
- **({"data": data} if data is not None else {}), **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.grid)
- def grid(b=None, which='major', axis='both', **kwargs):
- return gca().grid(b=b, which=which, axis=axis, **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.hexbin)
- def hexbin(
- x, y, C=None, gridsize=100, bins=None, xscale='linear',
- yscale='linear', extent=None, cmap=None, norm=None, vmin=None,
- vmax=None, alpha=None, linewidths=None, edgecolors='face',
- reduce_C_function=np.mean, mincnt=None, marginals=False, *,
- data=None, **kwargs):
- __ret = gca().hexbin(
- x, y, C=C, gridsize=gridsize, bins=bins, xscale=xscale,
- yscale=yscale, extent=extent, cmap=cmap, norm=norm, vmin=vmin,
- vmax=vmax, alpha=alpha, linewidths=linewidths,
- edgecolors=edgecolors, reduce_C_function=reduce_C_function,
- mincnt=mincnt, marginals=marginals, **({"data": data} if data
- is not None else {}), **kwargs)
- sci(__ret)
- return __ret
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.hist)
- def hist(
- x, bins=None, range=None, density=False, weights=None,
- cumulative=False, bottom=None, histtype='bar', align='mid',
- orientation='vertical', rwidth=None, log=False, color=None,
- label=None, stacked=False, *, data=None, **kwargs):
- return gca().hist(
- x, bins=bins, range=range, density=density, weights=weights,
- cumulative=cumulative, bottom=bottom, histtype=histtype,
- align=align, orientation=orientation, rwidth=rwidth, log=log,
- color=color, label=label, stacked=stacked, **({"data": data}
- if data is not None else {}), **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.hist2d)
- def hist2d(
- x, y, bins=10, range=None, density=False, weights=None,
- cmin=None, cmax=None, *, data=None, **kwargs):
- __ret = gca().hist2d(
- x, y, bins=bins, range=range, density=density,
- weights=weights, cmin=cmin, cmax=cmax, **({"data": data} if
- data is not None else {}), **kwargs)
- sci(__ret[-1])
- return __ret
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.hlines)
- def hlines(
- y, xmin, xmax, colors='k', linestyles='solid', label='', *,
- data=None, **kwargs):
- return gca().hlines(
- y, xmin, xmax, colors=colors, linestyles=linestyles,
- label=label, **({"data": data} if data is not None else {}),
- **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.imshow)
- def imshow(
- X, cmap=None, norm=None, aspect=None, interpolation=None,
- alpha=None, vmin=None, vmax=None, origin=None, extent=None,
- shape=cbook.deprecation._deprecated_parameter, filternorm=1,
- filterrad=4.0, imlim=cbook.deprecation._deprecated_parameter,
- resample=None, url=None, *, data=None, **kwargs):
- __ret = gca().imshow(
- X, cmap=cmap, norm=norm, aspect=aspect,
- interpolation=interpolation, alpha=alpha, vmin=vmin,
- vmax=vmax, origin=origin, extent=extent, shape=shape,
- filternorm=filternorm, filterrad=filterrad, imlim=imlim,
- resample=resample, url=url, **({"data": data} if data is not
- None else {}), **kwargs)
- sci(__ret)
- return __ret
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.legend)
- def legend(*args, **kwargs):
- return gca().legend(*args, **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.locator_params)
- def locator_params(axis='both', tight=None, **kwargs):
- return gca().locator_params(axis=axis, tight=tight, **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.loglog)
- def loglog(*args, **kwargs):
- return gca().loglog(*args, **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.magnitude_spectrum)
- def magnitude_spectrum(
- x, Fs=None, Fc=None, window=None, pad_to=None, sides=None,
- scale=None, *, data=None, **kwargs):
- return gca().magnitude_spectrum(
- x, Fs=Fs, Fc=Fc, window=window, pad_to=pad_to, sides=sides,
- scale=scale, **({"data": data} if data is not None else {}),
- **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.margins)
- def margins(*margins, x=None, y=None, tight=True):
- return gca().margins(*margins, x=x, y=y, tight=tight)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.minorticks_off)
- def minorticks_off():
- return gca().minorticks_off()
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.minorticks_on)
- def minorticks_on():
- return gca().minorticks_on()
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.pcolor)
- def pcolor(
- *args, alpha=None, norm=None, cmap=None, vmin=None,
- vmax=None, data=None, **kwargs):
- __ret = gca().pcolor(
- *args, alpha=alpha, norm=norm, cmap=cmap, vmin=vmin,
- vmax=vmax, **({"data": data} if data is not None else {}),
- **kwargs)
- sci(__ret)
- return __ret
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.pcolormesh)
- def pcolormesh(
- *args, alpha=None, norm=None, cmap=None, vmin=None,
- vmax=None, shading='flat', antialiased=False, data=None,
- **kwargs):
- __ret = gca().pcolormesh(
- *args, alpha=alpha, norm=norm, cmap=cmap, vmin=vmin,
- vmax=vmax, shading=shading, antialiased=antialiased,
- **({"data": data} if data is not None else {}), **kwargs)
- sci(__ret)
- return __ret
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.phase_spectrum)
- def phase_spectrum(
- x, Fs=None, Fc=None, window=None, pad_to=None, sides=None, *,
- data=None, **kwargs):
- return gca().phase_spectrum(
- x, Fs=Fs, Fc=Fc, window=window, pad_to=pad_to, sides=sides,
- **({"data": data} if data is not None else {}), **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.pie)
- def pie(
- x, explode=None, labels=None, colors=None, autopct=None,
- pctdistance=0.6, shadow=False, labeldistance=1.1,
- startangle=None, radius=None, counterclock=True,
- wedgeprops=None, textprops=None, center=(0, 0), frame=False,
- rotatelabels=False, *, data=None):
- return gca().pie(
- x, explode=explode, labels=labels, colors=colors,
- autopct=autopct, pctdistance=pctdistance, shadow=shadow,
- labeldistance=labeldistance, startangle=startangle,
- radius=radius, counterclock=counterclock,
- wedgeprops=wedgeprops, textprops=textprops, center=center,
- frame=frame, rotatelabels=rotatelabels, **({"data": data} if
- data is not None else {}))
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.plot)
- def plot(*args, scalex=True, scaley=True, data=None, **kwargs):
- return gca().plot(
- *args, scalex=scalex, scaley=scaley, **({"data": data} if data
- is not None else {}), **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.plot_date)
- def plot_date(
- x, y, fmt='o', tz=None, xdate=True, ydate=False, *,
- data=None, **kwargs):
- return gca().plot_date(
- x, y, fmt=fmt, tz=tz, xdate=xdate, ydate=ydate, **({"data":
- data} if data is not None else {}), **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.psd)
- def psd(
- x, NFFT=None, Fs=None, Fc=None, detrend=None, window=None,
- noverlap=None, pad_to=None, sides=None, scale_by_freq=None,
- return_line=None, *, data=None, **kwargs):
- return gca().psd(
- x, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, window=window,
- noverlap=noverlap, pad_to=pad_to, sides=sides,
- scale_by_freq=scale_by_freq, return_line=return_line,
- **({"data": data} if data is not None else {}), **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.quiver)
- def quiver(*args, data=None, **kw):
- __ret = gca().quiver(
- *args, **({"data": data} if data is not None else {}), **kw)
- sci(__ret)
- return __ret
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.quiverkey)
- def quiverkey(Q, X, Y, U, label, **kw):
- return gca().quiverkey(Q, X, Y, U, label, **kw)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.scatter)
- def scatter(
- x, y, s=None, c=None, marker=None, cmap=None, norm=None,
- vmin=None, vmax=None, alpha=None, linewidths=None,
- verts=cbook.deprecation._deprecated_parameter,
- edgecolors=None, *, plotnonfinite=False, data=None, **kwargs):
- __ret = gca().scatter(
- x, y, s=s, c=c, marker=marker, cmap=cmap, norm=norm,
- vmin=vmin, vmax=vmax, alpha=alpha, linewidths=linewidths,
- verts=verts, edgecolors=edgecolors,
- plotnonfinite=plotnonfinite, **({"data": data} if data is not
- None else {}), **kwargs)
- sci(__ret)
- return __ret
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.semilogx)
- def semilogx(*args, **kwargs):
- return gca().semilogx(*args, **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.semilogy)
- def semilogy(*args, **kwargs):
- return gca().semilogy(*args, **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.specgram)
- def specgram(
- x, NFFT=None, Fs=None, Fc=None, detrend=None, window=None,
- noverlap=None, cmap=None, xextent=None, pad_to=None,
- sides=None, scale_by_freq=None, mode=None, scale=None,
- vmin=None, vmax=None, *, data=None, **kwargs):
- __ret = gca().specgram(
- x, NFFT=NFFT, Fs=Fs, Fc=Fc, detrend=detrend, window=window,
- noverlap=noverlap, cmap=cmap, xextent=xextent, pad_to=pad_to,
- sides=sides, scale_by_freq=scale_by_freq, mode=mode,
- scale=scale, vmin=vmin, vmax=vmax, **({"data": data} if data
- is not None else {}), **kwargs)
- sci(__ret[-1])
- return __ret
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.spy)
- def spy(
- Z, precision=0, marker=None, markersize=None, aspect='equal',
- origin='upper', **kwargs):
- __ret = gca().spy(
- Z, precision=precision, marker=marker, markersize=markersize,
- aspect=aspect, origin=origin, **kwargs)
- if isinstance(__ret, cm.ScalarMappable): sci(__ret) # noqa
- return __ret
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.stackplot)
- def stackplot(
- x, *args, labels=(), colors=None, baseline='zero', data=None,
- **kwargs):
- return gca().stackplot(
- x, *args, labels=labels, colors=colors, baseline=baseline,
- **({"data": data} if data is not None else {}), **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.stem)
- def stem(
- *args, linefmt=None, markerfmt=None, basefmt=None, bottom=0,
- label=None, use_line_collection=False, data=None):
- return gca().stem(
- *args, linefmt=linefmt, markerfmt=markerfmt, basefmt=basefmt,
- bottom=bottom, label=label,
- use_line_collection=use_line_collection, **({"data": data} if
- data is not None else {}))
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.step)
- def step(x, y, *args, where='pre', data=None, **kwargs):
- return gca().step(
- x, y, *args, where=where, **({"data": data} if data is not
- None else {}), **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.streamplot)
- def streamplot(
- x, y, u, v, density=1, linewidth=None, color=None, cmap=None,
- norm=None, arrowsize=1, arrowstyle='-|>', minlength=0.1,
- transform=None, zorder=None, start_points=None, maxlength=4.0,
- integration_direction='both', *, data=None):
- __ret = gca().streamplot(
- x, y, u, v, density=density, linewidth=linewidth, color=color,
- cmap=cmap, norm=norm, arrowsize=arrowsize,
- arrowstyle=arrowstyle, minlength=minlength,
- transform=transform, zorder=zorder, start_points=start_points,
- maxlength=maxlength,
- integration_direction=integration_direction, **({"data": data}
- if data is not None else {}))
- sci(__ret.lines)
- return __ret
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.table)
- def table(
- cellText=None, cellColours=None, cellLoc='right',
- colWidths=None, rowLabels=None, rowColours=None,
- rowLoc='left', colLabels=None, colColours=None,
- colLoc='center', loc='bottom', bbox=None, edges='closed',
- **kwargs):
- return gca().table(
- cellText=cellText, cellColours=cellColours, cellLoc=cellLoc,
- colWidths=colWidths, rowLabels=rowLabels,
- rowColours=rowColours, rowLoc=rowLoc, colLabels=colLabels,
- colColours=colColours, colLoc=colLoc, loc=loc, bbox=bbox,
- edges=edges, **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.text)
- def text(
- x, y, s, fontdict=None,
- withdash=cbook.deprecation._deprecated_parameter, **kwargs):
- return gca().text(x, y, s, fontdict=fontdict, withdash=withdash, **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.tick_params)
- def tick_params(axis='both', **kwargs):
- return gca().tick_params(axis=axis, **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.ticklabel_format)
- def ticklabel_format(
- *, axis='both', style='', scilimits=None, useOffset=None,
- useLocale=None, useMathText=None):
- return gca().ticklabel_format(
- axis=axis, style=style, scilimits=scilimits,
- useOffset=useOffset, useLocale=useLocale,
- useMathText=useMathText)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.tricontour)
- def tricontour(*args, **kwargs):
- __ret = gca().tricontour(*args, **kwargs)
- if __ret._A is not None: sci(__ret) # noqa
- return __ret
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.tricontourf)
- def tricontourf(*args, **kwargs):
- __ret = gca().tricontourf(*args, **kwargs)
- if __ret._A is not None: sci(__ret) # noqa
- return __ret
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.tripcolor)
- def tripcolor(
- *args, alpha=1.0, norm=None, cmap=None, vmin=None, vmax=None,
- shading='flat', facecolors=None, **kwargs):
- __ret = gca().tripcolor(
- *args, alpha=alpha, norm=norm, cmap=cmap, vmin=vmin,
- vmax=vmax, shading=shading, facecolors=facecolors, **kwargs)
- sci(__ret)
- return __ret
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.triplot)
- def triplot(*args, **kwargs):
- return gca().triplot(*args, **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.violinplot)
- def violinplot(
- dataset, positions=None, vert=True, widths=0.5,
- showmeans=False, showextrema=True, showmedians=False,
- quantiles=None, points=100, bw_method=None, *, data=None):
- return gca().violinplot(
- dataset, positions=positions, vert=vert, widths=widths,
- showmeans=showmeans, showextrema=showextrema,
- showmedians=showmedians, quantiles=quantiles, points=points,
- bw_method=bw_method, **({"data": data} if data is not None
- else {}))
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.vlines)
- def vlines(
- x, ymin, ymax, colors='k', linestyles='solid', label='', *,
- data=None, **kwargs):
- return gca().vlines(
- x, ymin, ymax, colors=colors, linestyles=linestyles,
- label=label, **({"data": data} if data is not None else {}),
- **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.xcorr)
- def xcorr(
- x, y, normed=True, detrend=mlab.detrend_none, usevlines=True,
- maxlags=10, *, data=None, **kwargs):
- return gca().xcorr(
- x, y, normed=normed, detrend=detrend, usevlines=usevlines,
- maxlags=maxlags, **({"data": data} if data is not None else
- {}), **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes._sci)
- def sci(im):
- return gca()._sci(im)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.set_title)
- def title(label, fontdict=None, loc=None, pad=None, **kwargs):
- return gca().set_title(
- label, fontdict=fontdict, loc=loc, pad=pad, **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.set_xlabel)
- def xlabel(xlabel, fontdict=None, labelpad=None, **kwargs):
- return gca().set_xlabel(
- xlabel, fontdict=fontdict, labelpad=labelpad, **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.set_ylabel)
- def ylabel(ylabel, fontdict=None, labelpad=None, **kwargs):
- return gca().set_ylabel(
- ylabel, fontdict=fontdict, labelpad=labelpad, **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.set_xscale)
- def xscale(value, **kwargs):
- return gca().set_xscale(value, **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- @docstring.copy(Axes.set_yscale)
- def yscale(value, **kwargs):
- return gca().set_yscale(value, **kwargs)
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- def autumn():
- """
- Set the colormap to "autumn".
- This changes the default colormap as well as the colormap of the current
- image if there is one. See ``help(colormaps)`` for more information.
- """
- set_cmap("autumn")
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- def bone():
- """
- Set the colormap to "bone".
- This changes the default colormap as well as the colormap of the current
- image if there is one. See ``help(colormaps)`` for more information.
- """
- set_cmap("bone")
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- def cool():
- """
- Set the colormap to "cool".
- This changes the default colormap as well as the colormap of the current
- image if there is one. See ``help(colormaps)`` for more information.
- """
- set_cmap("cool")
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- def copper():
- """
- Set the colormap to "copper".
- This changes the default colormap as well as the colormap of the current
- image if there is one. See ``help(colormaps)`` for more information.
- """
- set_cmap("copper")
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- def flag():
- """
- Set the colormap to "flag".
- This changes the default colormap as well as the colormap of the current
- image if there is one. See ``help(colormaps)`` for more information.
- """
- set_cmap("flag")
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- def gray():
- """
- Set the colormap to "gray".
- This changes the default colormap as well as the colormap of the current
- image if there is one. See ``help(colormaps)`` for more information.
- """
- set_cmap("gray")
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- def hot():
- """
- Set the colormap to "hot".
- This changes the default colormap as well as the colormap of the current
- image if there is one. See ``help(colormaps)`` for more information.
- """
- set_cmap("hot")
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- def hsv():
- """
- Set the colormap to "hsv".
- This changes the default colormap as well as the colormap of the current
- image if there is one. See ``help(colormaps)`` for more information.
- """
- set_cmap("hsv")
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- def jet():
- """
- Set the colormap to "jet".
- This changes the default colormap as well as the colormap of the current
- image if there is one. See ``help(colormaps)`` for more information.
- """
- set_cmap("jet")
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- def pink():
- """
- Set the colormap to "pink".
- This changes the default colormap as well as the colormap of the current
- image if there is one. See ``help(colormaps)`` for more information.
- """
- set_cmap("pink")
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- def prism():
- """
- Set the colormap to "prism".
- This changes the default colormap as well as the colormap of the current
- image if there is one. See ``help(colormaps)`` for more information.
- """
- set_cmap("prism")
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- def spring():
- """
- Set the colormap to "spring".
- This changes the default colormap as well as the colormap of the current
- image if there is one. See ``help(colormaps)`` for more information.
- """
- set_cmap("spring")
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- def summer():
- """
- Set the colormap to "summer".
- This changes the default colormap as well as the colormap of the current
- image if there is one. See ``help(colormaps)`` for more information.
- """
- set_cmap("summer")
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- def winter():
- """
- Set the colormap to "winter".
- This changes the default colormap as well as the colormap of the current
- image if there is one. See ``help(colormaps)`` for more information.
- """
- set_cmap("winter")
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- def magma():
- """
- Set the colormap to "magma".
- This changes the default colormap as well as the colormap of the current
- image if there is one. See ``help(colormaps)`` for more information.
- """
- set_cmap("magma")
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- def inferno():
- """
- Set the colormap to "inferno".
- This changes the default colormap as well as the colormap of the current
- image if there is one. See ``help(colormaps)`` for more information.
- """
- set_cmap("inferno")
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- def plasma():
- """
- Set the colormap to "plasma".
- This changes the default colormap as well as the colormap of the current
- image if there is one. See ``help(colormaps)`` for more information.
- """
- set_cmap("plasma")
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- def viridis():
- """
- Set the colormap to "viridis".
- This changes the default colormap as well as the colormap of the current
- image if there is one. See ``help(colormaps)`` for more information.
- """
- set_cmap("viridis")
- # Autogenerated by boilerplate.py. Do not edit as changes will be lost.
- def nipy_spectral():
- """
- Set the colormap to "nipy_spectral".
- This changes the default colormap as well as the colormap of the current
- image if there is one. See ``help(colormaps)`` for more information.
- """
- set_cmap("nipy_spectral")
- _setup_pyplot_info_docstrings()
|