backend_bases.py 129 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585
  1. """
  2. Abstract base classes define the primitives that renderers and
  3. graphics contexts must implement to serve as a Matplotlib backend.
  4. `RendererBase`
  5. An abstract base class to handle drawing/rendering operations.
  6. `FigureCanvasBase`
  7. The abstraction layer that separates the `.Figure` from the backend
  8. specific details like a user interface drawing area.
  9. `GraphicsContextBase`
  10. An abstract base class that provides color, line styles, etc.
  11. `Event`
  12. The base class for all of the Matplotlib event handling. Derived classes
  13. such as `KeyEvent` and `MouseEvent` store the meta data like keys and
  14. buttons pressed, x and y locations in pixel and `~.axes.Axes` coordinates.
  15. `ShowBase`
  16. The base class for the ``Show`` class of each interactive backend; the
  17. 'show' callable is then set to ``Show.__call__``.
  18. `ToolContainerBase`
  19. The base class for the Toolbar class of each interactive backend.
  20. """
  21. from collections import namedtuple
  22. from contextlib import ExitStack, contextmanager, nullcontext
  23. from enum import Enum, IntEnum
  24. import functools
  25. import importlib
  26. import inspect
  27. import io
  28. import itertools
  29. import logging
  30. import os
  31. import pathlib
  32. import signal
  33. import socket
  34. import sys
  35. import time
  36. import weakref
  37. from weakref import WeakKeyDictionary
  38. import numpy as np
  39. import matplotlib as mpl
  40. from matplotlib import (
  41. _api, backend_tools as tools, cbook, colors, _docstring, text,
  42. _tight_bbox, transforms, widgets, is_interactive, rcParams)
  43. from matplotlib._pylab_helpers import Gcf
  44. from matplotlib.backend_managers import ToolManager
  45. from matplotlib.cbook import _setattr_cm
  46. from matplotlib.layout_engine import ConstrainedLayoutEngine
  47. from matplotlib.path import Path
  48. from matplotlib.texmanager import TexManager
  49. from matplotlib.transforms import Affine2D
  50. from matplotlib._enums import JoinStyle, CapStyle
  51. _log = logging.getLogger(__name__)
  52. _default_filetypes = {
  53. 'eps': 'Encapsulated Postscript',
  54. 'jpg': 'Joint Photographic Experts Group',
  55. 'jpeg': 'Joint Photographic Experts Group',
  56. 'pdf': 'Portable Document Format',
  57. 'pgf': 'PGF code for LaTeX',
  58. 'png': 'Portable Network Graphics',
  59. 'ps': 'Postscript',
  60. 'raw': 'Raw RGBA bitmap',
  61. 'rgba': 'Raw RGBA bitmap',
  62. 'svg': 'Scalable Vector Graphics',
  63. 'svgz': 'Scalable Vector Graphics',
  64. 'tif': 'Tagged Image File Format',
  65. 'tiff': 'Tagged Image File Format',
  66. 'webp': 'WebP Image Format',
  67. }
  68. _default_backends = {
  69. 'eps': 'matplotlib.backends.backend_ps',
  70. 'jpg': 'matplotlib.backends.backend_agg',
  71. 'jpeg': 'matplotlib.backends.backend_agg',
  72. 'pdf': 'matplotlib.backends.backend_pdf',
  73. 'pgf': 'matplotlib.backends.backend_pgf',
  74. 'png': 'matplotlib.backends.backend_agg',
  75. 'ps': 'matplotlib.backends.backend_ps',
  76. 'raw': 'matplotlib.backends.backend_agg',
  77. 'rgba': 'matplotlib.backends.backend_agg',
  78. 'svg': 'matplotlib.backends.backend_svg',
  79. 'svgz': 'matplotlib.backends.backend_svg',
  80. 'tif': 'matplotlib.backends.backend_agg',
  81. 'tiff': 'matplotlib.backends.backend_agg',
  82. 'webp': 'matplotlib.backends.backend_agg',
  83. }
  84. def register_backend(format, backend, description=None):
  85. """
  86. Register a backend for saving to a given file format.
  87. Parameters
  88. ----------
  89. format : str
  90. File extension
  91. backend : module string or canvas class
  92. Backend for handling file output
  93. description : str, default: ""
  94. Description of the file type.
  95. """
  96. if description is None:
  97. description = ''
  98. _default_backends[format] = backend
  99. _default_filetypes[format] = description
  100. def get_registered_canvas_class(format):
  101. """
  102. Return the registered default canvas for given file format.
  103. Handles deferred import of required backend.
  104. """
  105. if format not in _default_backends:
  106. return None
  107. backend_class = _default_backends[format]
  108. if isinstance(backend_class, str):
  109. backend_class = importlib.import_module(backend_class).FigureCanvas
  110. _default_backends[format] = backend_class
  111. return backend_class
  112. class RendererBase:
  113. """
  114. An abstract base class to handle drawing/rendering operations.
  115. The following methods must be implemented in the backend for full
  116. functionality (though just implementing `draw_path` alone would give a
  117. highly capable backend):
  118. * `draw_path`
  119. * `draw_image`
  120. * `draw_gouraud_triangles`
  121. The following methods *should* be implemented in the backend for
  122. optimization reasons:
  123. * `draw_text`
  124. * `draw_markers`
  125. * `draw_path_collection`
  126. * `draw_quad_mesh`
  127. """
  128. def __init__(self):
  129. super().__init__()
  130. self._texmanager = None
  131. self._text2path = text.TextToPath()
  132. self._raster_depth = 0
  133. self._rasterizing = False
  134. def open_group(self, s, gid=None):
  135. """
  136. Open a grouping element with label *s* and *gid* (if set) as id.
  137. Only used by the SVG renderer.
  138. """
  139. def close_group(self, s):
  140. """
  141. Close a grouping element with label *s*.
  142. Only used by the SVG renderer.
  143. """
  144. def draw_path(self, gc, path, transform, rgbFace=None):
  145. """Draw a `~.path.Path` instance using the given affine transform."""
  146. raise NotImplementedError
  147. def draw_markers(self, gc, marker_path, marker_trans, path,
  148. trans, rgbFace=None):
  149. """
  150. Draw a marker at each of *path*'s vertices (excluding control points).
  151. The base (fallback) implementation makes multiple calls to `draw_path`.
  152. Backends may want to override this method in order to draw the marker
  153. only once and reuse it multiple times.
  154. Parameters
  155. ----------
  156. gc : `.GraphicsContextBase`
  157. The graphics context.
  158. marker_path : `~matplotlib.path.Path`
  159. The path for the marker.
  160. marker_trans : `~matplotlib.transforms.Transform`
  161. An affine transform applied to the marker.
  162. path : `~matplotlib.path.Path`
  163. The locations to draw the markers.
  164. trans : `~matplotlib.transforms.Transform`
  165. An affine transform applied to the path.
  166. rgbFace : :mpltype:`color`, optional
  167. """
  168. for vertices, codes in path.iter_segments(trans, simplify=False):
  169. if len(vertices):
  170. x, y = vertices[-2:]
  171. self.draw_path(gc, marker_path,
  172. marker_trans +
  173. transforms.Affine2D().translate(x, y),
  174. rgbFace)
  175. def draw_path_collection(self, gc, master_transform, paths, all_transforms,
  176. offsets, offset_trans, facecolors, edgecolors,
  177. linewidths, linestyles, antialiaseds, urls,
  178. offset_position):
  179. """
  180. Draw a collection of *paths*.
  181. Each path is first transformed by the corresponding entry
  182. in *all_transforms* (a list of (3, 3) matrices) and then by
  183. *master_transform*. They are then translated by the corresponding
  184. entry in *offsets*, which has been first transformed by *offset_trans*.
  185. *facecolors*, *edgecolors*, *linewidths*, *linestyles*, and
  186. *antialiased* are lists that set the corresponding properties.
  187. *offset_position* is unused now, but the argument is kept for
  188. backwards compatibility.
  189. The base (fallback) implementation makes multiple calls to `draw_path`.
  190. Backends may want to override this in order to render each set of
  191. path data only once, and then reference that path multiple times with
  192. the different offsets, colors, styles etc. The generator methods
  193. `_iter_collection_raw_paths` and `_iter_collection` are provided to
  194. help with (and standardize) the implementation across backends. It
  195. is highly recommended to use those generators, so that changes to the
  196. behavior of `draw_path_collection` can be made globally.
  197. """
  198. path_ids = self._iter_collection_raw_paths(master_transform,
  199. paths, all_transforms)
  200. for xo, yo, path_id, gc0, rgbFace in self._iter_collection(
  201. gc, list(path_ids), offsets, offset_trans,
  202. facecolors, edgecolors, linewidths, linestyles,
  203. antialiaseds, urls, offset_position):
  204. path, transform = path_id
  205. # Only apply another translation if we have an offset, else we
  206. # reuse the initial transform.
  207. if xo != 0 or yo != 0:
  208. # The transformation can be used by multiple paths. Since
  209. # translate is a inplace operation, we need to copy the
  210. # transformation by .frozen() before applying the translation.
  211. transform = transform.frozen()
  212. transform.translate(xo, yo)
  213. self.draw_path(gc0, path, transform, rgbFace)
  214. def draw_quad_mesh(self, gc, master_transform, meshWidth, meshHeight,
  215. coordinates, offsets, offsetTrans, facecolors,
  216. antialiased, edgecolors):
  217. """
  218. Draw a quadmesh.
  219. The base (fallback) implementation converts the quadmesh to paths and
  220. then calls `draw_path_collection`.
  221. """
  222. from matplotlib.collections import QuadMesh
  223. paths = QuadMesh._convert_mesh_to_paths(coordinates)
  224. if edgecolors is None:
  225. edgecolors = facecolors
  226. linewidths = np.array([gc.get_linewidth()], float)
  227. return self.draw_path_collection(
  228. gc, master_transform, paths, [], offsets, offsetTrans, facecolors,
  229. edgecolors, linewidths, [], [antialiased], [None], 'screen')
  230. def draw_gouraud_triangles(self, gc, triangles_array, colors_array,
  231. transform):
  232. """
  233. Draw a series of Gouraud triangles.
  234. Parameters
  235. ----------
  236. gc : `.GraphicsContextBase`
  237. The graphics context.
  238. triangles_array : (N, 3, 2) array-like
  239. Array of *N* (x, y) points for the triangles.
  240. colors_array : (N, 3, 4) array-like
  241. Array of *N* RGBA colors for each point of the triangles.
  242. transform : `~matplotlib.transforms.Transform`
  243. An affine transform to apply to the points.
  244. """
  245. raise NotImplementedError
  246. def _iter_collection_raw_paths(self, master_transform, paths,
  247. all_transforms):
  248. """
  249. Helper method (along with `_iter_collection`) to implement
  250. `draw_path_collection` in a memory-efficient manner.
  251. This method yields all of the base path/transform combinations, given a
  252. master transform, a list of paths and list of transforms.
  253. The arguments should be exactly what is passed in to
  254. `draw_path_collection`.
  255. The backend should take each yielded path and transform and create an
  256. object that can be referenced (reused) later.
  257. """
  258. Npaths = len(paths)
  259. Ntransforms = len(all_transforms)
  260. N = max(Npaths, Ntransforms)
  261. if Npaths == 0:
  262. return
  263. transform = transforms.IdentityTransform()
  264. for i in range(N):
  265. path = paths[i % Npaths]
  266. if Ntransforms:
  267. transform = Affine2D(all_transforms[i % Ntransforms])
  268. yield path, transform + master_transform
  269. def _iter_collection_uses_per_path(self, paths, all_transforms,
  270. offsets, facecolors, edgecolors):
  271. """
  272. Compute how many times each raw path object returned by
  273. `_iter_collection_raw_paths` would be used when calling
  274. `_iter_collection`. This is intended for the backend to decide
  275. on the tradeoff between using the paths in-line and storing
  276. them once and reusing. Rounds up in case the number of uses
  277. is not the same for every path.
  278. """
  279. Npaths = len(paths)
  280. if Npaths == 0 or len(facecolors) == len(edgecolors) == 0:
  281. return 0
  282. Npath_ids = max(Npaths, len(all_transforms))
  283. N = max(Npath_ids, len(offsets))
  284. return (N + Npath_ids - 1) // Npath_ids
  285. def _iter_collection(self, gc, path_ids, offsets, offset_trans, facecolors,
  286. edgecolors, linewidths, linestyles,
  287. antialiaseds, urls, offset_position):
  288. """
  289. Helper method (along with `_iter_collection_raw_paths`) to implement
  290. `draw_path_collection` in a memory-efficient manner.
  291. This method yields all of the path, offset and graphics context
  292. combinations to draw the path collection. The caller should already
  293. have looped over the results of `_iter_collection_raw_paths` to draw
  294. this collection.
  295. The arguments should be the same as that passed into
  296. `draw_path_collection`, with the exception of *path_ids*, which is a
  297. list of arbitrary objects that the backend will use to reference one of
  298. the paths created in the `_iter_collection_raw_paths` stage.
  299. Each yielded result is of the form::
  300. xo, yo, path_id, gc, rgbFace
  301. where *xo*, *yo* is an offset; *path_id* is one of the elements of
  302. *path_ids*; *gc* is a graphics context and *rgbFace* is a color to
  303. use for filling the path.
  304. """
  305. Npaths = len(path_ids)
  306. Noffsets = len(offsets)
  307. N = max(Npaths, Noffsets)
  308. Nfacecolors = len(facecolors)
  309. Nedgecolors = len(edgecolors)
  310. Nlinewidths = len(linewidths)
  311. Nlinestyles = len(linestyles)
  312. Nurls = len(urls)
  313. if (Nfacecolors == 0 and Nedgecolors == 0) or Npaths == 0:
  314. return
  315. gc0 = self.new_gc()
  316. gc0.copy_properties(gc)
  317. def cycle_or_default(seq, default=None):
  318. # Cycle over *seq* if it is not empty; else always yield *default*.
  319. return (itertools.cycle(seq) if len(seq)
  320. else itertools.repeat(default))
  321. pathids = cycle_or_default(path_ids)
  322. toffsets = cycle_or_default(offset_trans.transform(offsets), (0, 0))
  323. fcs = cycle_or_default(facecolors)
  324. ecs = cycle_or_default(edgecolors)
  325. lws = cycle_or_default(linewidths)
  326. lss = cycle_or_default(linestyles)
  327. aas = cycle_or_default(antialiaseds)
  328. urls = cycle_or_default(urls)
  329. if Nedgecolors == 0:
  330. gc0.set_linewidth(0.0)
  331. for pathid, (xo, yo), fc, ec, lw, ls, aa, url in itertools.islice(
  332. zip(pathids, toffsets, fcs, ecs, lws, lss, aas, urls), N):
  333. if not (np.isfinite(xo) and np.isfinite(yo)):
  334. continue
  335. if Nedgecolors:
  336. if Nlinewidths:
  337. gc0.set_linewidth(lw)
  338. if Nlinestyles:
  339. gc0.set_dashes(*ls)
  340. if len(ec) == 4 and ec[3] == 0.0:
  341. gc0.set_linewidth(0)
  342. else:
  343. gc0.set_foreground(ec)
  344. if fc is not None and len(fc) == 4 and fc[3] == 0:
  345. fc = None
  346. gc0.set_antialiased(aa)
  347. if Nurls:
  348. gc0.set_url(url)
  349. yield xo, yo, pathid, gc0, fc
  350. gc0.restore()
  351. def get_image_magnification(self):
  352. """
  353. Get the factor by which to magnify images passed to `draw_image`.
  354. Allows a backend to have images at a different resolution to other
  355. artists.
  356. """
  357. return 1.0
  358. def draw_image(self, gc, x, y, im, transform=None):
  359. """
  360. Draw an RGBA image.
  361. Parameters
  362. ----------
  363. gc : `.GraphicsContextBase`
  364. A graphics context with clipping information.
  365. x : float
  366. The distance in physical units (i.e., dots or pixels) from the left
  367. hand side of the canvas.
  368. y : float
  369. The distance in physical units (i.e., dots or pixels) from the
  370. bottom side of the canvas.
  371. im : (N, M, 4) array of `numpy.uint8`
  372. An array of RGBA pixels.
  373. transform : `~matplotlib.transforms.Affine2DBase`
  374. If and only if the concrete backend is written such that
  375. `option_scale_image` returns ``True``, an affine transformation
  376. (i.e., an `.Affine2DBase`) *may* be passed to `draw_image`. The
  377. translation vector of the transformation is given in physical units
  378. (i.e., dots or pixels). Note that the transformation does not
  379. override *x* and *y*, and has to be applied *before* translating
  380. the result by *x* and *y* (this can be accomplished by adding *x*
  381. and *y* to the translation vector defined by *transform*).
  382. """
  383. raise NotImplementedError
  384. def option_image_nocomposite(self):
  385. """
  386. Return whether image composition by Matplotlib should be skipped.
  387. Raster backends should usually return False (letting the C-level
  388. rasterizer take care of image composition); vector backends should
  389. usually return ``not rcParams["image.composite_image"]``.
  390. """
  391. return False
  392. def option_scale_image(self):
  393. """
  394. Return whether arbitrary affine transformations in `draw_image` are
  395. supported (True for most vector backends).
  396. """
  397. return False
  398. def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None):
  399. """
  400. Draw a TeX instance.
  401. Parameters
  402. ----------
  403. gc : `.GraphicsContextBase`
  404. The graphics context.
  405. x : float
  406. The x location of the text in display coords.
  407. y : float
  408. The y location of the text baseline in display coords.
  409. s : str
  410. The TeX text string.
  411. prop : `~matplotlib.font_manager.FontProperties`
  412. The font properties.
  413. angle : float
  414. The rotation angle in degrees anti-clockwise.
  415. mtext : `~matplotlib.text.Text`
  416. The original text object to be rendered.
  417. """
  418. self._draw_text_as_path(gc, x, y, s, prop, angle, ismath="TeX")
  419. def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
  420. """
  421. Draw a text instance.
  422. Parameters
  423. ----------
  424. gc : `.GraphicsContextBase`
  425. The graphics context.
  426. x : float
  427. The x location of the text in display coords.
  428. y : float
  429. The y location of the text baseline in display coords.
  430. s : str
  431. The text string.
  432. prop : `~matplotlib.font_manager.FontProperties`
  433. The font properties.
  434. angle : float
  435. The rotation angle in degrees anti-clockwise.
  436. ismath : bool or "TeX"
  437. If True, use mathtext parser.
  438. mtext : `~matplotlib.text.Text`
  439. The original text object to be rendered.
  440. Notes
  441. -----
  442. **Notes for backend implementers:**
  443. `.RendererBase.draw_text` also supports passing "TeX" to the *ismath*
  444. parameter to use TeX rendering, but this is not required for actual
  445. rendering backends, and indeed many builtin backends do not support
  446. this. Rather, TeX rendering is provided by `~.RendererBase.draw_tex`.
  447. """
  448. self._draw_text_as_path(gc, x, y, s, prop, angle, ismath)
  449. def _draw_text_as_path(self, gc, x, y, s, prop, angle, ismath):
  450. """
  451. Draw the text by converting them to paths using `.TextToPath`.
  452. This private helper supports the same parameters as
  453. `~.RendererBase.draw_text`; setting *ismath* to "TeX" triggers TeX
  454. rendering.
  455. """
  456. text2path = self._text2path
  457. fontsize = self.points_to_pixels(prop.get_size_in_points())
  458. verts, codes = text2path.get_text_path(prop, s, ismath=ismath)
  459. path = Path(verts, codes)
  460. if self.flipy():
  461. width, height = self.get_canvas_width_height()
  462. transform = (Affine2D()
  463. .scale(fontsize / text2path.FONT_SCALE)
  464. .rotate_deg(angle)
  465. .translate(x, height - y))
  466. else:
  467. transform = (Affine2D()
  468. .scale(fontsize / text2path.FONT_SCALE)
  469. .rotate_deg(angle)
  470. .translate(x, y))
  471. color = gc.get_rgb()
  472. gc.set_linewidth(0.0)
  473. self.draw_path(gc, path, transform, rgbFace=color)
  474. def get_text_width_height_descent(self, s, prop, ismath):
  475. """
  476. Get the width, height, and descent (offset from the bottom to the baseline), in
  477. display coords, of the string *s* with `.FontProperties` *prop*.
  478. Whitespace at the start and the end of *s* is included in the reported width.
  479. """
  480. fontsize = prop.get_size_in_points()
  481. if ismath == 'TeX':
  482. # todo: handle properties
  483. return self.get_texmanager().get_text_width_height_descent(
  484. s, fontsize, renderer=self)
  485. dpi = self.points_to_pixels(72)
  486. if ismath:
  487. dims = self._text2path.mathtext_parser.parse(s, dpi, prop)
  488. return dims[0:3] # return width, height, descent
  489. flags = self._text2path._get_hinting_flag()
  490. font = self._text2path._get_font(prop)
  491. font.set_size(fontsize, dpi)
  492. # the width and height of unrotated string
  493. font.set_text(s, 0.0, flags=flags)
  494. w, h = font.get_width_height()
  495. d = font.get_descent()
  496. w /= 64.0 # convert from subpixels
  497. h /= 64.0
  498. d /= 64.0
  499. return w, h, d
  500. def flipy(self):
  501. """
  502. Return whether y values increase from top to bottom.
  503. Note that this only affects drawing of texts.
  504. """
  505. return True
  506. def get_canvas_width_height(self):
  507. """Return the canvas width and height in display coords."""
  508. return 1, 1
  509. def get_texmanager(self):
  510. """Return the `.TexManager` instance."""
  511. if self._texmanager is None:
  512. self._texmanager = TexManager()
  513. return self._texmanager
  514. def new_gc(self):
  515. """Return an instance of a `.GraphicsContextBase`."""
  516. return GraphicsContextBase()
  517. def points_to_pixels(self, points):
  518. """
  519. Convert points to display units.
  520. You need to override this function (unless your backend
  521. doesn't have a dpi, e.g., postscript or svg). Some imaging
  522. systems assume some value for pixels per inch::
  523. points to pixels = points * pixels_per_inch/72 * dpi/72
  524. Parameters
  525. ----------
  526. points : float or array-like
  527. Returns
  528. -------
  529. Points converted to pixels
  530. """
  531. return points
  532. def start_rasterizing(self):
  533. """
  534. Switch to the raster renderer.
  535. Used by `.MixedModeRenderer`.
  536. """
  537. def stop_rasterizing(self):
  538. """
  539. Switch back to the vector renderer and draw the contents of the raster
  540. renderer as an image on the vector renderer.
  541. Used by `.MixedModeRenderer`.
  542. """
  543. def start_filter(self):
  544. """
  545. Switch to a temporary renderer for image filtering effects.
  546. Currently only supported by the agg renderer.
  547. """
  548. def stop_filter(self, filter_func):
  549. """
  550. Switch back to the original renderer. The contents of the temporary
  551. renderer is processed with the *filter_func* and is drawn on the
  552. original renderer as an image.
  553. Currently only supported by the agg renderer.
  554. """
  555. def _draw_disabled(self):
  556. """
  557. Context manager to temporary disable drawing.
  558. This is used for getting the drawn size of Artists. This lets us
  559. run the draw process to update any Python state but does not pay the
  560. cost of the draw_XYZ calls on the canvas.
  561. """
  562. no_ops = {
  563. meth_name: lambda *args, **kwargs: None
  564. for meth_name in dir(RendererBase)
  565. if (meth_name.startswith("draw_")
  566. or meth_name in ["open_group", "close_group"])
  567. }
  568. return _setattr_cm(self, **no_ops)
  569. class GraphicsContextBase:
  570. """An abstract base class that provides color, line styles, etc."""
  571. def __init__(self):
  572. self._alpha = 1.0
  573. self._forced_alpha = False # if True, _alpha overrides A from RGBA
  574. self._antialiased = 1 # use 0, 1 not True, False for extension code
  575. self._capstyle = CapStyle('butt')
  576. self._cliprect = None
  577. self._clippath = None
  578. self._dashes = 0, None
  579. self._joinstyle = JoinStyle('round')
  580. self._linestyle = 'solid'
  581. self._linewidth = 1
  582. self._rgb = (0.0, 0.0, 0.0, 1.0)
  583. self._hatch = None
  584. self._hatch_color = colors.to_rgba(rcParams['hatch.color'])
  585. self._hatch_linewidth = rcParams['hatch.linewidth']
  586. self._url = None
  587. self._gid = None
  588. self._snap = None
  589. self._sketch = None
  590. def copy_properties(self, gc):
  591. """Copy properties from *gc* to self."""
  592. self._alpha = gc._alpha
  593. self._forced_alpha = gc._forced_alpha
  594. self._antialiased = gc._antialiased
  595. self._capstyle = gc._capstyle
  596. self._cliprect = gc._cliprect
  597. self._clippath = gc._clippath
  598. self._dashes = gc._dashes
  599. self._joinstyle = gc._joinstyle
  600. self._linestyle = gc._linestyle
  601. self._linewidth = gc._linewidth
  602. self._rgb = gc._rgb
  603. self._hatch = gc._hatch
  604. self._hatch_color = gc._hatch_color
  605. self._hatch_linewidth = gc._hatch_linewidth
  606. self._url = gc._url
  607. self._gid = gc._gid
  608. self._snap = gc._snap
  609. self._sketch = gc._sketch
  610. def restore(self):
  611. """
  612. Restore the graphics context from the stack - needed only
  613. for backends that save graphics contexts on a stack.
  614. """
  615. def get_alpha(self):
  616. """
  617. Return the alpha value used for blending - not supported on all
  618. backends.
  619. """
  620. return self._alpha
  621. def get_antialiased(self):
  622. """Return whether the object should try to do antialiased rendering."""
  623. return self._antialiased
  624. def get_capstyle(self):
  625. """Return the `.CapStyle`."""
  626. return self._capstyle.name
  627. def get_clip_rectangle(self):
  628. """
  629. Return the clip rectangle as a `~matplotlib.transforms.Bbox` instance.
  630. """
  631. return self._cliprect
  632. def get_clip_path(self):
  633. """
  634. Return the clip path in the form (path, transform), where path
  635. is a `~.path.Path` instance, and transform is
  636. an affine transform to apply to the path before clipping.
  637. """
  638. if self._clippath is not None:
  639. tpath, tr = self._clippath.get_transformed_path_and_affine()
  640. if np.all(np.isfinite(tpath.vertices)):
  641. return tpath, tr
  642. else:
  643. _log.warning("Ill-defined clip_path detected. Returning None.")
  644. return None, None
  645. return None, None
  646. def get_dashes(self):
  647. """
  648. Return the dash style as an (offset, dash-list) pair.
  649. See `.set_dashes` for details.
  650. Default value is (None, None).
  651. """
  652. return self._dashes
  653. def get_forced_alpha(self):
  654. """
  655. Return whether the value given by get_alpha() should be used to
  656. override any other alpha-channel values.
  657. """
  658. return self._forced_alpha
  659. def get_joinstyle(self):
  660. """Return the `.JoinStyle`."""
  661. return self._joinstyle.name
  662. def get_linewidth(self):
  663. """Return the line width in points."""
  664. return self._linewidth
  665. def get_rgb(self):
  666. """Return a tuple of three or four floats from 0-1."""
  667. return self._rgb
  668. def get_url(self):
  669. """Return a url if one is set, None otherwise."""
  670. return self._url
  671. def get_gid(self):
  672. """Return the object identifier if one is set, None otherwise."""
  673. return self._gid
  674. def get_snap(self):
  675. """
  676. Return the snap setting, which can be:
  677. * True: snap vertices to the nearest pixel center
  678. * False: leave vertices as-is
  679. * None: (auto) If the path contains only rectilinear line segments,
  680. round to the nearest pixel center
  681. """
  682. return self._snap
  683. def set_alpha(self, alpha):
  684. """
  685. Set the alpha value used for blending - not supported on all backends.
  686. If ``alpha=None`` (the default), the alpha components of the
  687. foreground and fill colors will be used to set their respective
  688. transparencies (where applicable); otherwise, ``alpha`` will override
  689. them.
  690. """
  691. if alpha is not None:
  692. self._alpha = alpha
  693. self._forced_alpha = True
  694. else:
  695. self._alpha = 1.0
  696. self._forced_alpha = False
  697. self.set_foreground(self._rgb, isRGBA=True)
  698. def set_antialiased(self, b):
  699. """Set whether object should be drawn with antialiased rendering."""
  700. # Use ints to make life easier on extension code trying to read the gc.
  701. self._antialiased = int(bool(b))
  702. @_docstring.interpd
  703. def set_capstyle(self, cs):
  704. """
  705. Set how to draw endpoints of lines.
  706. Parameters
  707. ----------
  708. cs : `.CapStyle` or %(CapStyle)s
  709. """
  710. self._capstyle = CapStyle(cs)
  711. def set_clip_rectangle(self, rectangle):
  712. """Set the clip rectangle to a `.Bbox` or None."""
  713. self._cliprect = rectangle
  714. def set_clip_path(self, path):
  715. """Set the clip path to a `.TransformedPath` or None."""
  716. _api.check_isinstance((transforms.TransformedPath, None), path=path)
  717. self._clippath = path
  718. def set_dashes(self, dash_offset, dash_list):
  719. """
  720. Set the dash style for the gc.
  721. Parameters
  722. ----------
  723. dash_offset : float
  724. Distance, in points, into the dash pattern at which to
  725. start the pattern. It is usually set to 0.
  726. dash_list : array-like or None
  727. The on-off sequence as points. None specifies a solid line. All
  728. values must otherwise be non-negative (:math:`\\ge 0`).
  729. Notes
  730. -----
  731. See p. 666 of the PostScript
  732. `Language Reference
  733. <https://www.adobe.com/jp/print/postscript/pdfs/PLRM.pdf>`_
  734. for more info.
  735. """
  736. if dash_list is not None:
  737. dl = np.asarray(dash_list)
  738. if np.any(dl < 0.0):
  739. raise ValueError(
  740. "All values in the dash list must be non-negative")
  741. if dl.size and not np.any(dl > 0.0):
  742. raise ValueError(
  743. 'At least one value in the dash list must be positive')
  744. self._dashes = dash_offset, dash_list
  745. def set_foreground(self, fg, isRGBA=False):
  746. """
  747. Set the foreground color.
  748. Parameters
  749. ----------
  750. fg : :mpltype:`color`
  751. isRGBA : bool
  752. If *fg* is known to be an ``(r, g, b, a)`` tuple, *isRGBA* can be
  753. set to True to improve performance.
  754. """
  755. if self._forced_alpha and isRGBA:
  756. self._rgb = fg[:3] + (self._alpha,)
  757. elif self._forced_alpha:
  758. self._rgb = colors.to_rgba(fg, self._alpha)
  759. elif isRGBA:
  760. self._rgb = fg
  761. else:
  762. self._rgb = colors.to_rgba(fg)
  763. @_docstring.interpd
  764. def set_joinstyle(self, js):
  765. """
  766. Set how to draw connections between line segments.
  767. Parameters
  768. ----------
  769. js : `.JoinStyle` or %(JoinStyle)s
  770. """
  771. self._joinstyle = JoinStyle(js)
  772. def set_linewidth(self, w):
  773. """Set the linewidth in points."""
  774. self._linewidth = float(w)
  775. def set_url(self, url):
  776. """Set the url for links in compatible backends."""
  777. self._url = url
  778. def set_gid(self, id):
  779. """Set the id."""
  780. self._gid = id
  781. def set_snap(self, snap):
  782. """
  783. Set the snap setting which may be:
  784. * True: snap vertices to the nearest pixel center
  785. * False: leave vertices as-is
  786. * None: (auto) If the path contains only rectilinear line segments,
  787. round to the nearest pixel center
  788. """
  789. self._snap = snap
  790. def set_hatch(self, hatch):
  791. """Set the hatch style (for fills)."""
  792. self._hatch = hatch
  793. def get_hatch(self):
  794. """Get the current hatch style."""
  795. return self._hatch
  796. def get_hatch_path(self, density=6.0):
  797. """Return a `.Path` for the current hatch."""
  798. hatch = self.get_hatch()
  799. if hatch is None:
  800. return None
  801. return Path.hatch(hatch, density)
  802. def get_hatch_color(self):
  803. """Get the hatch color."""
  804. return self._hatch_color
  805. def set_hatch_color(self, hatch_color):
  806. """Set the hatch color."""
  807. self._hatch_color = hatch_color
  808. def get_hatch_linewidth(self):
  809. """Get the hatch linewidth."""
  810. return self._hatch_linewidth
  811. def set_hatch_linewidth(self, hatch_linewidth):
  812. """Set the hatch linewidth."""
  813. self._hatch_linewidth = hatch_linewidth
  814. def get_sketch_params(self):
  815. """
  816. Return the sketch parameters for the artist.
  817. Returns
  818. -------
  819. tuple or `None`
  820. A 3-tuple with the following elements:
  821. * ``scale``: The amplitude of the wiggle perpendicular to the
  822. source line.
  823. * ``length``: The length of the wiggle along the line.
  824. * ``randomness``: The scale factor by which the length is
  825. shrunken or expanded.
  826. May return `None` if no sketch parameters were set.
  827. """
  828. return self._sketch
  829. def set_sketch_params(self, scale=None, length=None, randomness=None):
  830. """
  831. Set the sketch parameters.
  832. Parameters
  833. ----------
  834. scale : float, optional
  835. The amplitude of the wiggle perpendicular to the source line, in
  836. pixels. If scale is `None`, or not provided, no sketch filter will
  837. be provided.
  838. length : float, default: 128
  839. The length of the wiggle along the line, in pixels.
  840. randomness : float, default: 16
  841. The scale factor by which the length is shrunken or expanded.
  842. """
  843. self._sketch = (
  844. None if scale is None
  845. else (scale, length or 128., randomness or 16.))
  846. class TimerBase:
  847. """
  848. A base class for providing timer events, useful for things animations.
  849. Backends need to implement a few specific methods in order to use their
  850. own timing mechanisms so that the timer events are integrated into their
  851. event loops.
  852. Subclasses must override the following methods:
  853. - ``_timer_start``: Backend-specific code for starting the timer.
  854. - ``_timer_stop``: Backend-specific code for stopping the timer.
  855. Subclasses may additionally override the following methods:
  856. - ``_timer_set_single_shot``: Code for setting the timer to single shot
  857. operating mode, if supported by the timer object. If not, the `Timer`
  858. class itself will store the flag and the ``_on_timer`` method should be
  859. overridden to support such behavior.
  860. - ``_timer_set_interval``: Code for setting the interval on the timer, if
  861. there is a method for doing so on the timer object.
  862. - ``_on_timer``: The internal function that any timer object should call,
  863. which will handle the task of running all callbacks that have been set.
  864. """
  865. def __init__(self, interval=None, callbacks=None):
  866. """
  867. Parameters
  868. ----------
  869. interval : int, default: 1000ms
  870. The time between timer events in milliseconds. Will be stored as
  871. ``timer.interval``.
  872. callbacks : list[tuple[callable, tuple, dict]]
  873. List of (func, args, kwargs) tuples that will be called upon timer
  874. events. This list is accessible as ``timer.callbacks`` and can be
  875. manipulated directly, or the functions `~.TimerBase.add_callback`
  876. and `~.TimerBase.remove_callback` can be used.
  877. """
  878. self.callbacks = [] if callbacks is None else callbacks.copy()
  879. # Set .interval and not ._interval to go through the property setter.
  880. self.interval = 1000 if interval is None else interval
  881. self.single_shot = False
  882. def __del__(self):
  883. """Need to stop timer and possibly disconnect timer."""
  884. self._timer_stop()
  885. @_api.delete_parameter("3.9", "interval", alternative="timer.interval")
  886. def start(self, interval=None):
  887. """
  888. Start the timer object.
  889. Parameters
  890. ----------
  891. interval : int, optional
  892. Timer interval in milliseconds; overrides a previously set interval
  893. if provided.
  894. """
  895. if interval is not None:
  896. self.interval = interval
  897. self._timer_start()
  898. def stop(self):
  899. """Stop the timer."""
  900. self._timer_stop()
  901. def _timer_start(self):
  902. pass
  903. def _timer_stop(self):
  904. pass
  905. @property
  906. def interval(self):
  907. """The time between timer events, in milliseconds."""
  908. return self._interval
  909. @interval.setter
  910. def interval(self, interval):
  911. # Force to int since none of the backends actually support fractional
  912. # milliseconds, and some error or give warnings.
  913. # Some backends also fail when interval == 0, so ensure >= 1 msec
  914. interval = max(int(interval), 1)
  915. self._interval = interval
  916. self._timer_set_interval()
  917. @property
  918. def single_shot(self):
  919. """Whether this timer should stop after a single run."""
  920. return self._single
  921. @single_shot.setter
  922. def single_shot(self, ss):
  923. self._single = ss
  924. self._timer_set_single_shot()
  925. def add_callback(self, func, *args, **kwargs):
  926. """
  927. Register *func* to be called by timer when the event fires. Any
  928. additional arguments provided will be passed to *func*.
  929. This function returns *func*, which makes it possible to use it as a
  930. decorator.
  931. """
  932. self.callbacks.append((func, args, kwargs))
  933. return func
  934. def remove_callback(self, func, *args, **kwargs):
  935. """
  936. Remove *func* from list of callbacks.
  937. *args* and *kwargs* are optional and used to distinguish between copies
  938. of the same function registered to be called with different arguments.
  939. This behavior is deprecated. In the future, ``*args, **kwargs`` won't
  940. be considered anymore; to keep a specific callback removable by itself,
  941. pass it to `add_callback` as a `functools.partial` object.
  942. """
  943. if args or kwargs:
  944. _api.warn_deprecated(
  945. "3.1", message="In a future version, Timer.remove_callback "
  946. "will not take *args, **kwargs anymore, but remove all "
  947. "callbacks where the callable matches; to keep a specific "
  948. "callback removable by itself, pass it to add_callback as a "
  949. "functools.partial object.")
  950. self.callbacks.remove((func, args, kwargs))
  951. else:
  952. funcs = [c[0] for c in self.callbacks]
  953. if func in funcs:
  954. self.callbacks.pop(funcs.index(func))
  955. def _timer_set_interval(self):
  956. """Used to set interval on underlying timer object."""
  957. def _timer_set_single_shot(self):
  958. """Used to set single shot on underlying timer object."""
  959. def _on_timer(self):
  960. """
  961. Runs all function that have been registered as callbacks. Functions
  962. can return False (or 0) if they should not be called any more. If there
  963. are no callbacks, the timer is automatically stopped.
  964. """
  965. for func, args, kwargs in self.callbacks:
  966. ret = func(*args, **kwargs)
  967. # docstring above explains why we use `if ret == 0` here,
  968. # instead of `if not ret`.
  969. # This will also catch `ret == False` as `False == 0`
  970. # but does not annoy the linters
  971. # https://docs.python.org/3/library/stdtypes.html#boolean-values
  972. if ret == 0:
  973. self.callbacks.remove((func, args, kwargs))
  974. if len(self.callbacks) == 0:
  975. self.stop()
  976. class Event:
  977. """
  978. A Matplotlib event.
  979. The following attributes are defined and shown with their default values.
  980. Subclasses may define additional attributes.
  981. Attributes
  982. ----------
  983. name : str
  984. The event name.
  985. canvas : `FigureCanvasBase`
  986. The backend-specific canvas instance generating the event.
  987. guiEvent
  988. The GUI event that triggered the Matplotlib event.
  989. """
  990. def __init__(self, name, canvas, guiEvent=None):
  991. self.name = name
  992. self.canvas = canvas
  993. self.guiEvent = guiEvent
  994. def _process(self):
  995. """Process this event on ``self.canvas``, then unset ``guiEvent``."""
  996. self.canvas.callbacks.process(self.name, self)
  997. self.guiEvent = None
  998. class DrawEvent(Event):
  999. """
  1000. An event triggered by a draw operation on the canvas.
  1001. In most backends, callbacks subscribed to this event will be fired after
  1002. the rendering is complete but before the screen is updated. Any extra
  1003. artists drawn to the canvas's renderer will be reflected without an
  1004. explicit call to ``blit``.
  1005. .. warning::
  1006. Calling ``canvas.draw`` and ``canvas.blit`` in these callbacks may
  1007. not be safe with all backends and may cause infinite recursion.
  1008. A DrawEvent has a number of special attributes in addition to those defined
  1009. by the parent `Event` class.
  1010. Attributes
  1011. ----------
  1012. renderer : `RendererBase`
  1013. The renderer for the draw event.
  1014. """
  1015. def __init__(self, name, canvas, renderer):
  1016. super().__init__(name, canvas)
  1017. self.renderer = renderer
  1018. class ResizeEvent(Event):
  1019. """
  1020. An event triggered by a canvas resize.
  1021. A ResizeEvent has a number of special attributes in addition to those
  1022. defined by the parent `Event` class.
  1023. Attributes
  1024. ----------
  1025. width : int
  1026. Width of the canvas in pixels.
  1027. height : int
  1028. Height of the canvas in pixels.
  1029. """
  1030. def __init__(self, name, canvas):
  1031. super().__init__(name, canvas)
  1032. self.width, self.height = canvas.get_width_height()
  1033. class CloseEvent(Event):
  1034. """An event triggered by a figure being closed."""
  1035. class LocationEvent(Event):
  1036. """
  1037. An event that has a screen location.
  1038. A LocationEvent has a number of special attributes in addition to those
  1039. defined by the parent `Event` class.
  1040. Attributes
  1041. ----------
  1042. x, y : int or None
  1043. Event location in pixels from bottom left of canvas.
  1044. inaxes : `~matplotlib.axes.Axes` or None
  1045. The `~.axes.Axes` instance over which the mouse is, if any.
  1046. xdata, ydata : float or None
  1047. Data coordinates of the mouse within *inaxes*, or *None* if the mouse
  1048. is not over an Axes.
  1049. modifiers : frozenset
  1050. The keyboard modifiers currently being pressed (except for KeyEvent).
  1051. """
  1052. _last_axes_ref = None
  1053. def __init__(self, name, canvas, x, y, guiEvent=None, *, modifiers=None):
  1054. super().__init__(name, canvas, guiEvent=guiEvent)
  1055. # x position - pixels from left of canvas
  1056. self.x = int(x) if x is not None else x
  1057. # y position - pixels from right of canvas
  1058. self.y = int(y) if y is not None else y
  1059. self.inaxes = None # the Axes instance the mouse is over
  1060. self.xdata = None # x coord of mouse in data coords
  1061. self.ydata = None # y coord of mouse in data coords
  1062. self.modifiers = frozenset(modifiers if modifiers is not None else [])
  1063. if x is None or y is None:
  1064. # cannot check if event was in Axes if no (x, y) info
  1065. return
  1066. self._set_inaxes(self.canvas.inaxes((x, y))
  1067. if self.canvas.mouse_grabber is None else
  1068. self.canvas.mouse_grabber,
  1069. (x, y))
  1070. # Splitting _set_inaxes out is useful for the axes_leave_event handler: it
  1071. # needs to generate synthetic LocationEvents with manually-set inaxes. In
  1072. # that latter case, xy has already been cast to int so it can directly be
  1073. # read from self.x, self.y; in the normal case, however, it is more
  1074. # accurate to pass the untruncated float x, y values passed to the ctor.
  1075. def _set_inaxes(self, inaxes, xy=None):
  1076. self.inaxes = inaxes
  1077. if inaxes is not None:
  1078. try:
  1079. self.xdata, self.ydata = inaxes.transData.inverted().transform(
  1080. xy if xy is not None else (self.x, self.y))
  1081. except ValueError:
  1082. pass
  1083. class MouseButton(IntEnum):
  1084. LEFT = 1
  1085. MIDDLE = 2
  1086. RIGHT = 3
  1087. BACK = 8
  1088. FORWARD = 9
  1089. class MouseEvent(LocationEvent):
  1090. """
  1091. A mouse event ('button_press_event', 'button_release_event', \
  1092. 'scroll_event', 'motion_notify_event').
  1093. A MouseEvent has a number of special attributes in addition to those
  1094. defined by the parent `Event` and `LocationEvent` classes.
  1095. Attributes
  1096. ----------
  1097. button : None or `MouseButton` or {'up', 'down'}
  1098. The button pressed. 'up' and 'down' are used for scroll events.
  1099. Note that LEFT and RIGHT actually refer to the "primary" and
  1100. "secondary" buttons, i.e. if the user inverts their left and right
  1101. buttons ("left-handed setting") then the LEFT button will be the one
  1102. physically on the right.
  1103. If this is unset, *name* is "scroll_event", and *step* is nonzero, then
  1104. this will be set to "up" or "down" depending on the sign of *step*.
  1105. buttons : None or frozenset
  1106. For 'motion_notify_event', the mouse buttons currently being pressed
  1107. (a set of zero or more MouseButtons);
  1108. for other events, None.
  1109. .. note::
  1110. For 'motion_notify_event', this attribute is more accurate than
  1111. the ``button`` (singular) attribute, which is obtained from the last
  1112. 'button_press_event' or 'button_release_event' that occurred within
  1113. the canvas (and thus 1. be wrong if the last change in mouse state
  1114. occurred when the canvas did not have focus, and 2. cannot report
  1115. when multiple buttons are pressed).
  1116. This attribute is not set for 'button_press_event' and
  1117. 'button_release_event' because GUI toolkits are inconsistent as to
  1118. whether they report the button state *before* or *after* the
  1119. press/release occurred.
  1120. .. warning::
  1121. On macOS, the Tk backends only report a single button even if
  1122. multiple buttons are pressed.
  1123. key : None or str
  1124. The key pressed when the mouse event triggered, e.g. 'shift'.
  1125. See `KeyEvent`.
  1126. .. warning::
  1127. This key is currently obtained from the last 'key_press_event' or
  1128. 'key_release_event' that occurred within the canvas. Thus, if the
  1129. last change of keyboard state occurred while the canvas did not have
  1130. focus, this attribute will be wrong. On the other hand, the
  1131. ``modifiers`` attribute should always be correct, but it can only
  1132. report on modifier keys.
  1133. step : float
  1134. The number of scroll steps (positive for 'up', negative for 'down').
  1135. This applies only to 'scroll_event' and defaults to 0 otherwise.
  1136. dblclick : bool
  1137. Whether the event is a double-click. This applies only to
  1138. 'button_press_event' and is False otherwise. In particular, it's
  1139. not used in 'button_release_event'.
  1140. Examples
  1141. --------
  1142. ::
  1143. def on_press(event):
  1144. print('you pressed', event.button, event.xdata, event.ydata)
  1145. cid = fig.canvas.mpl_connect('button_press_event', on_press)
  1146. """
  1147. def __init__(self, name, canvas, x, y, button=None, key=None,
  1148. step=0, dblclick=False, guiEvent=None, *,
  1149. buttons=None, modifiers=None):
  1150. super().__init__(
  1151. name, canvas, x, y, guiEvent=guiEvent, modifiers=modifiers)
  1152. if button in MouseButton.__members__.values():
  1153. button = MouseButton(button)
  1154. if name == "scroll_event" and button is None:
  1155. if step > 0:
  1156. button = "up"
  1157. elif step < 0:
  1158. button = "down"
  1159. self.button = button
  1160. if name == "motion_notify_event":
  1161. self.buttons = frozenset(buttons if buttons is not None else [])
  1162. else:
  1163. # We don't support 'buttons' for button_press/release_event because
  1164. # toolkits are inconsistent as to whether they report the state
  1165. # before or after the event.
  1166. if buttons:
  1167. raise ValueError(
  1168. "'buttons' is only supported for 'motion_notify_event'")
  1169. self.buttons = None
  1170. self.key = key
  1171. self.step = step
  1172. self.dblclick = dblclick
  1173. def __str__(self):
  1174. return (f"{self.name}: "
  1175. f"xy=({self.x}, {self.y}) xydata=({self.xdata}, {self.ydata}) "
  1176. f"button={self.button} dblclick={self.dblclick} "
  1177. f"inaxes={self.inaxes}")
  1178. class PickEvent(Event):
  1179. """
  1180. A pick event.
  1181. This event is fired when the user picks a location on the canvas
  1182. sufficiently close to an artist that has been made pickable with
  1183. `.Artist.set_picker`.
  1184. A PickEvent has a number of special attributes in addition to those defined
  1185. by the parent `Event` class.
  1186. Attributes
  1187. ----------
  1188. mouseevent : `MouseEvent`
  1189. The mouse event that generated the pick.
  1190. artist : `~matplotlib.artist.Artist`
  1191. The picked artist. Note that artists are not pickable by default
  1192. (see `.Artist.set_picker`).
  1193. other
  1194. Additional attributes may be present depending on the type of the
  1195. picked object; e.g., a `.Line2D` pick may define different extra
  1196. attributes than a `.PatchCollection` pick.
  1197. Examples
  1198. --------
  1199. Bind a function ``on_pick()`` to pick events, that prints the coordinates
  1200. of the picked data point::
  1201. ax.plot(np.rand(100), 'o', picker=5) # 5 points tolerance
  1202. def on_pick(event):
  1203. line = event.artist
  1204. xdata, ydata = line.get_data()
  1205. ind = event.ind
  1206. print(f'on pick line: {xdata[ind]:.3f}, {ydata[ind]:.3f}')
  1207. cid = fig.canvas.mpl_connect('pick_event', on_pick)
  1208. """
  1209. def __init__(self, name, canvas, mouseevent, artist,
  1210. guiEvent=None, **kwargs):
  1211. if guiEvent is None:
  1212. guiEvent = mouseevent.guiEvent
  1213. super().__init__(name, canvas, guiEvent)
  1214. self.mouseevent = mouseevent
  1215. self.artist = artist
  1216. self.__dict__.update(kwargs)
  1217. class KeyEvent(LocationEvent):
  1218. """
  1219. A key event (key press, key release).
  1220. A KeyEvent has a number of special attributes in addition to those defined
  1221. by the parent `Event` and `LocationEvent` classes.
  1222. Attributes
  1223. ----------
  1224. key : None or str
  1225. The key(s) pressed. Could be *None*, a single case sensitive Unicode
  1226. character ("g", "G", "#", etc.), a special key ("control", "shift",
  1227. "f1", "up", etc.) or a combination of the above (e.g., "ctrl+alt+g",
  1228. "ctrl+alt+G").
  1229. Notes
  1230. -----
  1231. Modifier keys will be prefixed to the pressed key and will be in the order
  1232. "ctrl", "alt", "super". The exception to this rule is when the pressed key
  1233. is itself a modifier key, therefore "ctrl+alt" and "alt+control" can both
  1234. be valid key values.
  1235. Examples
  1236. --------
  1237. ::
  1238. def on_key(event):
  1239. print('you pressed', event.key, event.xdata, event.ydata)
  1240. cid = fig.canvas.mpl_connect('key_press_event', on_key)
  1241. """
  1242. def __init__(self, name, canvas, key, x=0, y=0, guiEvent=None):
  1243. super().__init__(name, canvas, x, y, guiEvent=guiEvent)
  1244. self.key = key
  1245. # Default callback for key events.
  1246. def _key_handler(event):
  1247. # Dead reckoning of key.
  1248. if event.name == "key_press_event":
  1249. event.canvas._key = event.key
  1250. elif event.name == "key_release_event":
  1251. event.canvas._key = None
  1252. # Default callback for mouse events.
  1253. def _mouse_handler(event):
  1254. # Dead-reckoning of button and key.
  1255. if event.name == "button_press_event":
  1256. event.canvas._button = event.button
  1257. elif event.name == "button_release_event":
  1258. event.canvas._button = None
  1259. elif event.name == "motion_notify_event" and event.button is None:
  1260. event.button = event.canvas._button
  1261. if event.key is None:
  1262. event.key = event.canvas._key
  1263. # Emit axes_enter/axes_leave.
  1264. if event.name == "motion_notify_event":
  1265. last_ref = LocationEvent._last_axes_ref
  1266. last_axes = last_ref() if last_ref else None
  1267. if last_axes != event.inaxes:
  1268. if last_axes is not None:
  1269. # Create a synthetic LocationEvent for the axes_leave_event.
  1270. # Its inaxes attribute needs to be manually set (because the
  1271. # cursor is actually *out* of that Axes at that point); this is
  1272. # done with the internal _set_inaxes method which ensures that
  1273. # the xdata and ydata attributes are also correct.
  1274. try:
  1275. canvas = last_axes.get_figure(root=True).canvas
  1276. leave_event = LocationEvent(
  1277. "axes_leave_event", canvas,
  1278. event.x, event.y, event.guiEvent,
  1279. modifiers=event.modifiers)
  1280. leave_event._set_inaxes(last_axes)
  1281. canvas.callbacks.process("axes_leave_event", leave_event)
  1282. except Exception:
  1283. pass # The last canvas may already have been torn down.
  1284. if event.inaxes is not None:
  1285. event.canvas.callbacks.process("axes_enter_event", event)
  1286. LocationEvent._last_axes_ref = (
  1287. weakref.ref(event.inaxes) if event.inaxes else None)
  1288. def _get_renderer(figure, print_method=None):
  1289. """
  1290. Get the renderer that would be used to save a `.Figure`.
  1291. If you need a renderer without any active draw methods use
  1292. renderer._draw_disabled to temporary patch them out at your call site.
  1293. """
  1294. # This is implemented by triggering a draw, then immediately jumping out of
  1295. # Figure.draw() by raising an exception.
  1296. class Done(Exception):
  1297. pass
  1298. def _draw(renderer): raise Done(renderer)
  1299. with cbook._setattr_cm(figure, draw=_draw), ExitStack() as stack:
  1300. if print_method is None:
  1301. fmt = figure.canvas.get_default_filetype()
  1302. # Even for a canvas' default output type, a canvas switch may be
  1303. # needed, e.g. for FigureCanvasBase.
  1304. print_method = stack.enter_context(
  1305. figure.canvas._switch_canvas_and_return_print_method(fmt))
  1306. try:
  1307. print_method(io.BytesIO())
  1308. except Done as exc:
  1309. renderer, = exc.args
  1310. return renderer
  1311. else:
  1312. raise RuntimeError(f"{print_method} did not call Figure.draw, so "
  1313. f"no renderer is available")
  1314. def _no_output_draw(figure):
  1315. # _no_output_draw was promoted to the figure level, but
  1316. # keep this here in case someone was calling it...
  1317. figure.draw_without_rendering()
  1318. def _is_non_interactive_terminal_ipython(ip):
  1319. """
  1320. Return whether we are in a terminal IPython, but non interactive.
  1321. When in _terminal_ IPython, ip.parent will have and `interact` attribute,
  1322. if this attribute is False we do not setup eventloop integration as the
  1323. user will _not_ interact with IPython. In all other case (ZMQKernel, or is
  1324. interactive), we do.
  1325. """
  1326. return (hasattr(ip, 'parent')
  1327. and (ip.parent is not None)
  1328. and getattr(ip.parent, 'interact', None) is False)
  1329. @contextmanager
  1330. def _allow_interrupt(prepare_notifier, handle_sigint):
  1331. """
  1332. A context manager that allows terminating a plot by sending a SIGINT. It
  1333. is necessary because the running backend prevents the Python interpreter
  1334. from running and processing signals (i.e., to raise a KeyboardInterrupt).
  1335. To solve this, one needs to somehow wake up the interpreter and make it
  1336. close the plot window. We do this by using the signal.set_wakeup_fd()
  1337. function which organizes a write of the signal number into a socketpair.
  1338. A backend-specific function, *prepare_notifier*, arranges to listen to
  1339. the pair's read socket while the event loop is running. (If it returns a
  1340. notifier object, that object is kept alive while the context manager runs.)
  1341. If SIGINT was indeed caught, after exiting the on_signal() function the
  1342. interpreter reacts to the signal according to the handler function which
  1343. had been set up by a signal.signal() call; here, we arrange to call the
  1344. backend-specific *handle_sigint* function, passing the notifier object
  1345. as returned by prepare_notifier(). Finally, we call the old SIGINT
  1346. handler with the same arguments that were given to our custom handler.
  1347. We do this only if the old handler for SIGINT was not None, which means
  1348. that a non-python handler was installed, i.e. in Julia, and not SIG_IGN
  1349. which means we should ignore the interrupts.
  1350. Parameters
  1351. ----------
  1352. prepare_notifier : Callable[[socket.socket], object]
  1353. handle_sigint : Callable[[object], object]
  1354. """
  1355. old_sigint_handler = signal.getsignal(signal.SIGINT)
  1356. if old_sigint_handler in (None, signal.SIG_IGN, signal.SIG_DFL):
  1357. yield
  1358. return
  1359. handler_args = None
  1360. wsock, rsock = socket.socketpair()
  1361. wsock.setblocking(False)
  1362. rsock.setblocking(False)
  1363. old_wakeup_fd = signal.set_wakeup_fd(wsock.fileno())
  1364. notifier = prepare_notifier(rsock)
  1365. def save_args_and_handle_sigint(*args):
  1366. nonlocal handler_args, notifier
  1367. handler_args = args
  1368. handle_sigint(notifier)
  1369. notifier = None
  1370. signal.signal(signal.SIGINT, save_args_and_handle_sigint)
  1371. try:
  1372. yield
  1373. finally:
  1374. wsock.close()
  1375. rsock.close()
  1376. signal.set_wakeup_fd(old_wakeup_fd)
  1377. signal.signal(signal.SIGINT, old_sigint_handler)
  1378. if handler_args is not None:
  1379. old_sigint_handler(*handler_args)
  1380. class FigureCanvasBase:
  1381. """
  1382. The canvas the figure renders into.
  1383. Attributes
  1384. ----------
  1385. figure : `~matplotlib.figure.Figure`
  1386. A high-level figure instance.
  1387. """
  1388. # Set to one of {"qt", "gtk3", "gtk4", "wx", "tk", "macosx"} if an
  1389. # interactive framework is required, or None otherwise.
  1390. required_interactive_framework = None
  1391. # The manager class instantiated by new_manager.
  1392. # (This is defined as a classproperty because the manager class is
  1393. # currently defined *after* the canvas class, but one could also assign
  1394. # ``FigureCanvasBase.manager_class = FigureManagerBase``
  1395. # after defining both classes.)
  1396. manager_class = _api.classproperty(lambda cls: FigureManagerBase)
  1397. events = [
  1398. 'resize_event',
  1399. 'draw_event',
  1400. 'key_press_event',
  1401. 'key_release_event',
  1402. 'button_press_event',
  1403. 'button_release_event',
  1404. 'scroll_event',
  1405. 'motion_notify_event',
  1406. 'pick_event',
  1407. 'figure_enter_event',
  1408. 'figure_leave_event',
  1409. 'axes_enter_event',
  1410. 'axes_leave_event',
  1411. 'close_event'
  1412. ]
  1413. fixed_dpi = None
  1414. filetypes = _default_filetypes
  1415. @_api.classproperty
  1416. def supports_blit(cls):
  1417. """If this Canvas sub-class supports blitting."""
  1418. return (hasattr(cls, "copy_from_bbox")
  1419. and hasattr(cls, "restore_region"))
  1420. def __init__(self, figure=None):
  1421. from matplotlib.figure import Figure
  1422. self._fix_ipython_backend2gui()
  1423. self._is_idle_drawing = True
  1424. self._is_saving = False
  1425. if figure is None:
  1426. figure = Figure()
  1427. figure.set_canvas(self)
  1428. self.figure = figure
  1429. self.manager = None
  1430. self.widgetlock = widgets.LockDraw()
  1431. self._button = None # the button pressed
  1432. self._key = None # the key pressed
  1433. self.mouse_grabber = None # the Axes currently grabbing mouse
  1434. self.toolbar = None # NavigationToolbar2 will set me
  1435. self._is_idle_drawing = False
  1436. # We don't want to scale up the figure DPI more than once.
  1437. figure._original_dpi = figure.dpi
  1438. self._device_pixel_ratio = 1
  1439. super().__init__() # Typically the GUI widget init (if any).
  1440. callbacks = property(lambda self: self.figure._canvas_callbacks)
  1441. button_pick_id = property(lambda self: self.figure._button_pick_id)
  1442. scroll_pick_id = property(lambda self: self.figure._scroll_pick_id)
  1443. @classmethod
  1444. @functools.cache
  1445. def _fix_ipython_backend2gui(cls):
  1446. # Fix hard-coded module -> toolkit mapping in IPython (used for
  1447. # `ipython --auto`). This cannot be done at import time due to
  1448. # ordering issues, so we do it when creating a canvas, and should only
  1449. # be done once per class (hence the `cache`).
  1450. # This function will not be needed when Python 3.12, the latest version
  1451. # supported by IPython < 8.24, reaches end-of-life in late 2028.
  1452. # At that time this function can be made a no-op and deprecated.
  1453. mod_ipython = sys.modules.get("IPython")
  1454. if mod_ipython is None or mod_ipython.version_info[:2] >= (8, 24):
  1455. # Use of backend2gui is not needed for IPython >= 8.24 as the
  1456. # functionality has been moved to Matplotlib.
  1457. return
  1458. import IPython
  1459. ip = IPython.get_ipython()
  1460. if not ip:
  1461. return
  1462. from IPython.core import pylabtools as pt
  1463. if (not hasattr(pt, "backend2gui")
  1464. or not hasattr(ip, "enable_matplotlib")):
  1465. # In case we ever move the patch to IPython and remove these APIs,
  1466. # don't break on our side.
  1467. return
  1468. backend2gui_rif = {
  1469. "qt": "qt",
  1470. "gtk3": "gtk3",
  1471. "gtk4": "gtk4",
  1472. "wx": "wx",
  1473. "macosx": "osx",
  1474. }.get(cls.required_interactive_framework)
  1475. if backend2gui_rif:
  1476. if _is_non_interactive_terminal_ipython(ip):
  1477. ip.enable_gui(backend2gui_rif)
  1478. @classmethod
  1479. def new_manager(cls, figure, num):
  1480. """
  1481. Create a new figure manager for *figure*, using this canvas class.
  1482. Notes
  1483. -----
  1484. This method should not be reimplemented in subclasses. If
  1485. custom manager creation logic is needed, please reimplement
  1486. ``FigureManager.create_with_canvas``.
  1487. """
  1488. return cls.manager_class.create_with_canvas(cls, figure, num)
  1489. @contextmanager
  1490. def _idle_draw_cntx(self):
  1491. self._is_idle_drawing = True
  1492. try:
  1493. yield
  1494. finally:
  1495. self._is_idle_drawing = False
  1496. def is_saving(self):
  1497. """
  1498. Return whether the renderer is in the process of saving
  1499. to a file, rather than rendering for an on-screen buffer.
  1500. """
  1501. return self._is_saving
  1502. def blit(self, bbox=None):
  1503. """Blit the canvas in bbox (default entire canvas)."""
  1504. def inaxes(self, xy):
  1505. """
  1506. Return the topmost visible `~.axes.Axes` containing the point *xy*.
  1507. Parameters
  1508. ----------
  1509. xy : (float, float)
  1510. (x, y) pixel positions from left/bottom of the canvas.
  1511. Returns
  1512. -------
  1513. `~matplotlib.axes.Axes` or None
  1514. The topmost visible Axes containing the point, or None if there
  1515. is no Axes at the point.
  1516. """
  1517. axes_list = [a for a in self.figure.get_axes()
  1518. if a.patch.contains_point(xy) and a.get_visible()]
  1519. if axes_list:
  1520. axes = cbook._topmost_artist(axes_list)
  1521. else:
  1522. axes = None
  1523. return axes
  1524. def grab_mouse(self, ax):
  1525. """
  1526. Set the child `~.axes.Axes` which is grabbing the mouse events.
  1527. Usually called by the widgets themselves. It is an error to call this
  1528. if the mouse is already grabbed by another Axes.
  1529. """
  1530. if self.mouse_grabber not in (None, ax):
  1531. raise RuntimeError("Another Axes already grabs mouse input")
  1532. self.mouse_grabber = ax
  1533. def release_mouse(self, ax):
  1534. """
  1535. Release the mouse grab held by the `~.axes.Axes` *ax*.
  1536. Usually called by the widgets. It is ok to call this even if *ax*
  1537. doesn't have the mouse grab currently.
  1538. """
  1539. if self.mouse_grabber is ax:
  1540. self.mouse_grabber = None
  1541. def set_cursor(self, cursor):
  1542. """
  1543. Set the current cursor.
  1544. This may have no effect if the backend does not display anything.
  1545. If required by the backend, this method should trigger an update in
  1546. the backend event loop after the cursor is set, as this method may be
  1547. called e.g. before a long-running task during which the GUI is not
  1548. updated.
  1549. Parameters
  1550. ----------
  1551. cursor : `.Cursors`
  1552. The cursor to display over the canvas. Note: some backends may
  1553. change the cursor for the entire window.
  1554. """
  1555. def draw(self, *args, **kwargs):
  1556. """
  1557. Render the `.Figure`.
  1558. This method must walk the artist tree, even if no output is produced,
  1559. because it triggers deferred work that users may want to access
  1560. before saving output to disk. For example computing limits,
  1561. auto-limits, and tick values.
  1562. """
  1563. def draw_idle(self, *args, **kwargs):
  1564. """
  1565. Request a widget redraw once control returns to the GUI event loop.
  1566. Even if multiple calls to `draw_idle` occur before control returns
  1567. to the GUI event loop, the figure will only be rendered once.
  1568. Notes
  1569. -----
  1570. Backends may choose to override the method and implement their own
  1571. strategy to prevent multiple renderings.
  1572. """
  1573. if not self._is_idle_drawing:
  1574. with self._idle_draw_cntx():
  1575. self.draw(*args, **kwargs)
  1576. @property
  1577. def device_pixel_ratio(self):
  1578. """
  1579. The ratio of physical to logical pixels used for the canvas on screen.
  1580. By default, this is 1, meaning physical and logical pixels are the same
  1581. size. Subclasses that support High DPI screens may set this property to
  1582. indicate that said ratio is different. All Matplotlib interaction,
  1583. unless working directly with the canvas, remains in logical pixels.
  1584. """
  1585. return self._device_pixel_ratio
  1586. def _set_device_pixel_ratio(self, ratio):
  1587. """
  1588. Set the ratio of physical to logical pixels used for the canvas.
  1589. Subclasses that support High DPI screens can set this property to
  1590. indicate that said ratio is different. The canvas itself will be
  1591. created at the physical size, while the client side will use the
  1592. logical size. Thus the DPI of the Figure will change to be scaled by
  1593. this ratio. Implementations that support High DPI screens should use
  1594. physical pixels for events so that transforms back to Axes space are
  1595. correct.
  1596. By default, this is 1, meaning physical and logical pixels are the same
  1597. size.
  1598. Parameters
  1599. ----------
  1600. ratio : float
  1601. The ratio of logical to physical pixels used for the canvas.
  1602. Returns
  1603. -------
  1604. bool
  1605. Whether the ratio has changed. Backends may interpret this as a
  1606. signal to resize the window, repaint the canvas, or change any
  1607. other relevant properties.
  1608. """
  1609. if self._device_pixel_ratio == ratio:
  1610. return False
  1611. # In cases with mixed resolution displays, we need to be careful if the
  1612. # device pixel ratio changes - in this case we need to resize the
  1613. # canvas accordingly. Some backends provide events that indicate a
  1614. # change in DPI, but those that don't will update this before drawing.
  1615. dpi = ratio * self.figure._original_dpi
  1616. self.figure._set_dpi(dpi, forward=False)
  1617. self._device_pixel_ratio = ratio
  1618. return True
  1619. def get_width_height(self, *, physical=False):
  1620. """
  1621. Return the figure width and height in integral points or pixels.
  1622. When the figure is used on High DPI screens (and the backend supports
  1623. it), the truncation to integers occurs after scaling by the device
  1624. pixel ratio.
  1625. Parameters
  1626. ----------
  1627. physical : bool, default: False
  1628. Whether to return true physical pixels or logical pixels. Physical
  1629. pixels may be used by backends that support HiDPI, but still
  1630. configure the canvas using its actual size.
  1631. Returns
  1632. -------
  1633. width, height : int
  1634. The size of the figure, in points or pixels, depending on the
  1635. backend.
  1636. """
  1637. return tuple(int(size / (1 if physical else self.device_pixel_ratio))
  1638. for size in self.figure.bbox.max)
  1639. @classmethod
  1640. def get_supported_filetypes(cls):
  1641. """Return dict of savefig file formats supported by this backend."""
  1642. return cls.filetypes
  1643. @classmethod
  1644. def get_supported_filetypes_grouped(cls):
  1645. """
  1646. Return a dict of savefig file formats supported by this backend,
  1647. where the keys are a file type name, such as 'Joint Photographic
  1648. Experts Group', and the values are a list of filename extensions used
  1649. for that filetype, such as ['jpg', 'jpeg'].
  1650. """
  1651. groupings = {}
  1652. for ext, name in cls.filetypes.items():
  1653. groupings.setdefault(name, []).append(ext)
  1654. groupings[name].sort()
  1655. return groupings
  1656. @contextmanager
  1657. def _switch_canvas_and_return_print_method(self, fmt, backend=None):
  1658. """
  1659. Context manager temporarily setting the canvas for saving the figure::
  1660. with (canvas._switch_canvas_and_return_print_method(fmt, backend)
  1661. as print_method):
  1662. # ``print_method`` is a suitable ``print_{fmt}`` method, and
  1663. # the figure's canvas is temporarily switched to the method's
  1664. # canvas within the with... block. ``print_method`` is also
  1665. # wrapped to suppress extra kwargs passed by ``print_figure``.
  1666. Parameters
  1667. ----------
  1668. fmt : str
  1669. If *backend* is None, then determine a suitable canvas class for
  1670. saving to format *fmt* -- either the current canvas class, if it
  1671. supports *fmt*, or whatever `get_registered_canvas_class` returns;
  1672. switch the figure canvas to that canvas class.
  1673. backend : str or None, default: None
  1674. If not None, switch the figure canvas to the ``FigureCanvas`` class
  1675. of the given backend.
  1676. """
  1677. canvas = None
  1678. if backend is not None:
  1679. # Return a specific canvas class, if requested.
  1680. from .backends.registry import backend_registry
  1681. canvas_class = backend_registry.load_backend_module(backend).FigureCanvas
  1682. if not hasattr(canvas_class, f"print_{fmt}"):
  1683. raise ValueError(
  1684. f"The {backend!r} backend does not support {fmt} output")
  1685. canvas = canvas_class(self.figure)
  1686. elif hasattr(self, f"print_{fmt}"):
  1687. # Return the current canvas if it supports the requested format.
  1688. canvas = self
  1689. else:
  1690. # Return a default canvas for the requested format, if it exists.
  1691. canvas_class = get_registered_canvas_class(fmt)
  1692. if canvas_class is None:
  1693. raise ValueError(
  1694. "Format {!r} is not supported (supported formats: {})".format(
  1695. fmt, ", ".join(sorted(self.get_supported_filetypes()))))
  1696. canvas = canvas_class(self.figure)
  1697. canvas._is_saving = self._is_saving
  1698. meth = getattr(canvas, f"print_{fmt}")
  1699. mod = (meth.func.__module__
  1700. if hasattr(meth, "func") # partialmethod, e.g. backend_wx.
  1701. else meth.__module__)
  1702. if mod.startswith(("matplotlib.", "mpl_toolkits.")):
  1703. optional_kws = { # Passed by print_figure for other renderers.
  1704. "dpi", "facecolor", "edgecolor", "orientation",
  1705. "bbox_inches_restore"}
  1706. skip = optional_kws - {*inspect.signature(meth).parameters}
  1707. print_method = functools.wraps(meth)(lambda *args, **kwargs: meth(
  1708. *args, **{k: v for k, v in kwargs.items() if k not in skip}))
  1709. else: # Let third-parties do as they see fit.
  1710. print_method = meth
  1711. try:
  1712. yield print_method
  1713. finally:
  1714. self.figure.canvas = self
  1715. def print_figure(
  1716. self, filename, dpi=None, facecolor=None, edgecolor=None,
  1717. orientation='portrait', format=None, *,
  1718. bbox_inches=None, pad_inches=None, bbox_extra_artists=None,
  1719. backend=None, **kwargs):
  1720. """
  1721. Render the figure to hardcopy. Set the figure patch face and edge
  1722. colors. This is useful because some of the GUIs have a gray figure
  1723. face color background and you'll probably want to override this on
  1724. hardcopy.
  1725. Parameters
  1726. ----------
  1727. filename : str or path-like or file-like
  1728. The file where the figure is saved.
  1729. dpi : float, default: :rc:`savefig.dpi`
  1730. The dots per inch to save the figure in.
  1731. facecolor : :mpltype:`color` or 'auto', default: :rc:`savefig.facecolor`
  1732. The facecolor of the figure. If 'auto', use the current figure
  1733. facecolor.
  1734. edgecolor : :mpltype:`color` or 'auto', default: :rc:`savefig.edgecolor`
  1735. The edgecolor of the figure. If 'auto', use the current figure
  1736. edgecolor.
  1737. orientation : {'landscape', 'portrait'}, default: 'portrait'
  1738. Only currently applies to PostScript printing.
  1739. format : str, optional
  1740. Force a specific file format. If not given, the format is inferred
  1741. from the *filename* extension, and if that fails from
  1742. :rc:`savefig.format`.
  1743. bbox_inches : 'tight' or `.Bbox`, default: :rc:`savefig.bbox`
  1744. Bounding box in inches: only the given portion of the figure is
  1745. saved. If 'tight', try to figure out the tight bbox of the figure.
  1746. pad_inches : float or 'layout', default: :rc:`savefig.pad_inches`
  1747. Amount of padding in inches around the figure when bbox_inches is
  1748. 'tight'. If 'layout' use the padding from the constrained or
  1749. compressed layout engine; ignored if one of those engines is not in
  1750. use.
  1751. bbox_extra_artists : list of `~matplotlib.artist.Artist`, optional
  1752. A list of extra artists that will be considered when the
  1753. tight bbox is calculated.
  1754. backend : str, optional
  1755. Use a non-default backend to render the file, e.g. to render a
  1756. png file with the "cairo" backend rather than the default "agg",
  1757. or a pdf file with the "pgf" backend rather than the default
  1758. "pdf". Note that the default backend is normally sufficient. See
  1759. :ref:`the-builtin-backends` for a list of valid backends for each
  1760. file format. Custom backends can be referenced as "module://...".
  1761. """
  1762. if format is None:
  1763. # get format from filename, or from backend's default filetype
  1764. if isinstance(filename, os.PathLike):
  1765. filename = os.fspath(filename)
  1766. if isinstance(filename, str):
  1767. format = os.path.splitext(filename)[1][1:]
  1768. if format is None or format == '':
  1769. format = self.get_default_filetype()
  1770. if isinstance(filename, str):
  1771. filename = filename.rstrip('.') + '.' + format
  1772. format = format.lower()
  1773. if dpi is None:
  1774. dpi = rcParams['savefig.dpi']
  1775. if dpi == 'figure':
  1776. dpi = getattr(self.figure, '_original_dpi', self.figure.dpi)
  1777. # Remove the figure manager, if any, to avoid resizing the GUI widget.
  1778. with (cbook._setattr_cm(self, manager=None),
  1779. self._switch_canvas_and_return_print_method(format, backend)
  1780. as print_method,
  1781. cbook._setattr_cm(self.figure, dpi=dpi),
  1782. cbook._setattr_cm(self.figure.canvas, _device_pixel_ratio=1),
  1783. cbook._setattr_cm(self.figure.canvas, _is_saving=True),
  1784. ExitStack() as stack):
  1785. for prop in ["facecolor", "edgecolor"]:
  1786. color = locals()[prop]
  1787. if color is None:
  1788. color = rcParams[f"savefig.{prop}"]
  1789. if not cbook._str_equal(color, "auto"):
  1790. stack.enter_context(self.figure._cm_set(**{prop: color}))
  1791. if bbox_inches is None:
  1792. bbox_inches = rcParams['savefig.bbox']
  1793. layout_engine = self.figure.get_layout_engine()
  1794. if layout_engine is not None or bbox_inches == "tight":
  1795. # we need to trigger a draw before printing to make sure
  1796. # CL works. "tight" also needs a draw to get the right
  1797. # locations:
  1798. renderer = _get_renderer(
  1799. self.figure,
  1800. functools.partial(
  1801. print_method, orientation=orientation)
  1802. )
  1803. # we do this instead of `self.figure.draw_without_rendering`
  1804. # so that we can inject the orientation
  1805. with getattr(renderer, "_draw_disabled", nullcontext)():
  1806. self.figure.draw(renderer)
  1807. if bbox_inches:
  1808. if bbox_inches == "tight":
  1809. bbox_inches = self.figure.get_tightbbox(
  1810. renderer, bbox_extra_artists=bbox_extra_artists)
  1811. if (isinstance(layout_engine, ConstrainedLayoutEngine) and
  1812. pad_inches == "layout"):
  1813. h_pad = layout_engine.get()["h_pad"]
  1814. w_pad = layout_engine.get()["w_pad"]
  1815. else:
  1816. if pad_inches in [None, "layout"]:
  1817. pad_inches = rcParams['savefig.pad_inches']
  1818. h_pad = w_pad = pad_inches
  1819. bbox_inches = bbox_inches.padded(w_pad, h_pad)
  1820. # call adjust_bbox to save only the given area
  1821. restore_bbox = _tight_bbox.adjust_bbox(
  1822. self.figure, bbox_inches, self.figure.canvas.fixed_dpi)
  1823. _bbox_inches_restore = (bbox_inches, restore_bbox)
  1824. else:
  1825. _bbox_inches_restore = None
  1826. # we have already done layout above, so turn it off:
  1827. stack.enter_context(self.figure._cm_set(layout_engine='none'))
  1828. try:
  1829. # _get_renderer may change the figure dpi (as vector formats
  1830. # force the figure dpi to 72), so we need to set it again here.
  1831. with cbook._setattr_cm(self.figure, dpi=dpi):
  1832. result = print_method(
  1833. filename,
  1834. facecolor=facecolor,
  1835. edgecolor=edgecolor,
  1836. orientation=orientation,
  1837. bbox_inches_restore=_bbox_inches_restore,
  1838. **kwargs)
  1839. finally:
  1840. if bbox_inches and restore_bbox:
  1841. restore_bbox()
  1842. return result
  1843. @classmethod
  1844. def get_default_filetype(cls):
  1845. """
  1846. Return the default savefig file format as specified in
  1847. :rc:`savefig.format`.
  1848. The returned string does not include a period. This method is
  1849. overridden in backends that only support a single file type.
  1850. """
  1851. return rcParams['savefig.format']
  1852. def get_default_filename(self):
  1853. """
  1854. Return a suitable default filename, including the extension.
  1855. """
  1856. default_basename = (
  1857. self.manager.get_window_title()
  1858. if self.manager is not None
  1859. else ''
  1860. )
  1861. default_basename = default_basename or 'image'
  1862. # Characters to be avoided in a NT path:
  1863. # https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#naming_conventions
  1864. # plus ' '
  1865. removed_chars = '<>:"/\\|?*\0 '
  1866. default_basename = default_basename.translate(
  1867. {ord(c): "_" for c in removed_chars})
  1868. default_filetype = self.get_default_filetype()
  1869. return f'{default_basename}.{default_filetype}'
  1870. def mpl_connect(self, s, func):
  1871. """
  1872. Bind function *func* to event *s*.
  1873. Parameters
  1874. ----------
  1875. s : str
  1876. One of the following events ids:
  1877. - 'button_press_event'
  1878. - 'button_release_event'
  1879. - 'draw_event'
  1880. - 'key_press_event'
  1881. - 'key_release_event'
  1882. - 'motion_notify_event'
  1883. - 'pick_event'
  1884. - 'resize_event'
  1885. - 'scroll_event'
  1886. - 'figure_enter_event',
  1887. - 'figure_leave_event',
  1888. - 'axes_enter_event',
  1889. - 'axes_leave_event'
  1890. - 'close_event'.
  1891. func : callable
  1892. The callback function to be executed, which must have the
  1893. signature::
  1894. def func(event: Event) -> Any
  1895. For the location events (button and key press/release), if the
  1896. mouse is over the Axes, the ``inaxes`` attribute of the event will
  1897. be set to the `~matplotlib.axes.Axes` the event occurs is over, and
  1898. additionally, the variables ``xdata`` and ``ydata`` attributes will
  1899. be set to the mouse location in data coordinates. See `.KeyEvent`
  1900. and `.MouseEvent` for more info.
  1901. .. note::
  1902. If func is a method, this only stores a weak reference to the
  1903. method. Thus, the figure does not influence the lifetime of
  1904. the associated object. Usually, you want to make sure that the
  1905. object is kept alive throughout the lifetime of the figure by
  1906. holding a reference to it.
  1907. Returns
  1908. -------
  1909. cid
  1910. A connection id that can be used with
  1911. `.FigureCanvasBase.mpl_disconnect`.
  1912. Examples
  1913. --------
  1914. ::
  1915. def on_press(event):
  1916. print('you pressed', event.button, event.xdata, event.ydata)
  1917. cid = canvas.mpl_connect('button_press_event', on_press)
  1918. """
  1919. return self.callbacks.connect(s, func)
  1920. def mpl_disconnect(self, cid):
  1921. """
  1922. Disconnect the callback with id *cid*.
  1923. Examples
  1924. --------
  1925. ::
  1926. cid = canvas.mpl_connect('button_press_event', on_press)
  1927. # ... later
  1928. canvas.mpl_disconnect(cid)
  1929. """
  1930. self.callbacks.disconnect(cid)
  1931. # Internal subclasses can override _timer_cls instead of new_timer, though
  1932. # this is not a public API for third-party subclasses.
  1933. _timer_cls = TimerBase
  1934. def new_timer(self, interval=None, callbacks=None):
  1935. """
  1936. Create a new backend-specific subclass of `.Timer`.
  1937. This is useful for getting periodic events through the backend's native
  1938. event loop. Implemented only for backends with GUIs.
  1939. Parameters
  1940. ----------
  1941. interval : int
  1942. Timer interval in milliseconds.
  1943. callbacks : list[tuple[callable, tuple, dict]]
  1944. Sequence of (func, args, kwargs) where ``func(*args, **kwargs)``
  1945. will be executed by the timer every *interval*.
  1946. Callbacks which return ``False`` or ``0`` will be removed from the
  1947. timer.
  1948. Examples
  1949. --------
  1950. >>> timer = fig.canvas.new_timer(callbacks=[(f1, (1,), {'a': 3})])
  1951. """
  1952. return self._timer_cls(interval=interval, callbacks=callbacks)
  1953. def flush_events(self):
  1954. """
  1955. Flush the GUI events for the figure.
  1956. Interactive backends need to reimplement this method.
  1957. """
  1958. def start_event_loop(self, timeout=0):
  1959. """
  1960. Start a blocking event loop.
  1961. Such an event loop is used by interactive functions, such as
  1962. `~.Figure.ginput` and `~.Figure.waitforbuttonpress`, to wait for
  1963. events.
  1964. The event loop blocks until a callback function triggers
  1965. `stop_event_loop`, or *timeout* is reached.
  1966. If *timeout* is 0 or negative, never timeout.
  1967. Only interactive backends need to reimplement this method and it relies
  1968. on `flush_events` being properly implemented.
  1969. Interactive backends should implement this in a more native way.
  1970. """
  1971. if timeout <= 0:
  1972. timeout = np.inf
  1973. timestep = 0.01
  1974. counter = 0
  1975. self._looping = True
  1976. while self._looping and counter * timestep < timeout:
  1977. self.flush_events()
  1978. time.sleep(timestep)
  1979. counter += 1
  1980. def stop_event_loop(self):
  1981. """
  1982. Stop the current blocking event loop.
  1983. Interactive backends need to reimplement this to match
  1984. `start_event_loop`
  1985. """
  1986. self._looping = False
  1987. def key_press_handler(event, canvas=None, toolbar=None):
  1988. """
  1989. Implement the default Matplotlib key bindings for the canvas and toolbar
  1990. described at :ref:`key-event-handling`.
  1991. Parameters
  1992. ----------
  1993. event : `KeyEvent`
  1994. A key press/release event.
  1995. canvas : `FigureCanvasBase`, default: ``event.canvas``
  1996. The backend-specific canvas instance. This parameter is kept for
  1997. back-compatibility, but, if set, should always be equal to
  1998. ``event.canvas``.
  1999. toolbar : `NavigationToolbar2`, default: ``event.canvas.toolbar``
  2000. The navigation cursor toolbar. This parameter is kept for
  2001. back-compatibility, but, if set, should always be equal to
  2002. ``event.canvas.toolbar``.
  2003. """
  2004. if event.key is None:
  2005. return
  2006. if canvas is None:
  2007. canvas = event.canvas
  2008. if toolbar is None:
  2009. toolbar = canvas.toolbar
  2010. # toggle fullscreen mode (default key 'f', 'ctrl + f')
  2011. if event.key in rcParams['keymap.fullscreen']:
  2012. try:
  2013. canvas.manager.full_screen_toggle()
  2014. except AttributeError:
  2015. pass
  2016. # quit the figure (default key 'ctrl+w')
  2017. if event.key in rcParams['keymap.quit']:
  2018. Gcf.destroy_fig(canvas.figure)
  2019. if event.key in rcParams['keymap.quit_all']:
  2020. Gcf.destroy_all()
  2021. if toolbar is not None:
  2022. # home or reset mnemonic (default key 'h', 'home' and 'r')
  2023. if event.key in rcParams['keymap.home']:
  2024. toolbar.home()
  2025. # forward / backward keys to enable left handed quick navigation
  2026. # (default key for backward: 'left', 'backspace' and 'c')
  2027. elif event.key in rcParams['keymap.back']:
  2028. toolbar.back()
  2029. # (default key for forward: 'right' and 'v')
  2030. elif event.key in rcParams['keymap.forward']:
  2031. toolbar.forward()
  2032. # pan mnemonic (default key 'p')
  2033. elif event.key in rcParams['keymap.pan']:
  2034. toolbar.pan()
  2035. toolbar._update_cursor(event)
  2036. # zoom mnemonic (default key 'o')
  2037. elif event.key in rcParams['keymap.zoom']:
  2038. toolbar.zoom()
  2039. toolbar._update_cursor(event)
  2040. # saving current figure (default key 's')
  2041. elif event.key in rcParams['keymap.save']:
  2042. toolbar.save_figure()
  2043. if event.inaxes is None:
  2044. return
  2045. # these bindings require the mouse to be over an Axes to trigger
  2046. def _get_uniform_gridstate(ticks):
  2047. # Return True/False if all grid lines are on or off, None if they are
  2048. # not all in the same state.
  2049. return (True if all(tick.gridline.get_visible() for tick in ticks) else
  2050. False if not any(tick.gridline.get_visible() for tick in ticks) else
  2051. None)
  2052. ax = event.inaxes
  2053. # toggle major grids in current Axes (default key 'g')
  2054. # Both here and below (for 'G'), we do nothing if *any* grid (major or
  2055. # minor, x or y) is not in a uniform state, to avoid messing up user
  2056. # customization.
  2057. if (event.key in rcParams['keymap.grid']
  2058. # Exclude minor grids not in a uniform state.
  2059. and None not in [_get_uniform_gridstate(ax.xaxis.minorTicks),
  2060. _get_uniform_gridstate(ax.yaxis.minorTicks)]):
  2061. x_state = _get_uniform_gridstate(ax.xaxis.majorTicks)
  2062. y_state = _get_uniform_gridstate(ax.yaxis.majorTicks)
  2063. cycle = [(False, False), (True, False), (True, True), (False, True)]
  2064. try:
  2065. x_state, y_state = (
  2066. cycle[(cycle.index((x_state, y_state)) + 1) % len(cycle)])
  2067. except ValueError:
  2068. # Exclude major grids not in a uniform state.
  2069. pass
  2070. else:
  2071. # If turning major grids off, also turn minor grids off.
  2072. ax.grid(x_state, which="major" if x_state else "both", axis="x")
  2073. ax.grid(y_state, which="major" if y_state else "both", axis="y")
  2074. canvas.draw_idle()
  2075. # toggle major and minor grids in current Axes (default key 'G')
  2076. if (event.key in rcParams['keymap.grid_minor']
  2077. # Exclude major grids not in a uniform state.
  2078. and None not in [_get_uniform_gridstate(ax.xaxis.majorTicks),
  2079. _get_uniform_gridstate(ax.yaxis.majorTicks)]):
  2080. x_state = _get_uniform_gridstate(ax.xaxis.minorTicks)
  2081. y_state = _get_uniform_gridstate(ax.yaxis.minorTicks)
  2082. cycle = [(False, False), (True, False), (True, True), (False, True)]
  2083. try:
  2084. x_state, y_state = (
  2085. cycle[(cycle.index((x_state, y_state)) + 1) % len(cycle)])
  2086. except ValueError:
  2087. # Exclude minor grids not in a uniform state.
  2088. pass
  2089. else:
  2090. ax.grid(x_state, which="both", axis="x")
  2091. ax.grid(y_state, which="both", axis="y")
  2092. canvas.draw_idle()
  2093. # toggle scaling of y-axes between 'log and 'linear' (default key 'l')
  2094. elif event.key in rcParams['keymap.yscale']:
  2095. scale = ax.get_yscale()
  2096. if scale == 'log':
  2097. ax.set_yscale('linear')
  2098. ax.get_figure(root=True).canvas.draw_idle()
  2099. elif scale == 'linear':
  2100. try:
  2101. ax.set_yscale('log')
  2102. except ValueError as exc:
  2103. _log.warning(str(exc))
  2104. ax.set_yscale('linear')
  2105. ax.get_figure(root=True).canvas.draw_idle()
  2106. # toggle scaling of x-axes between 'log and 'linear' (default key 'k')
  2107. elif event.key in rcParams['keymap.xscale']:
  2108. scalex = ax.get_xscale()
  2109. if scalex == 'log':
  2110. ax.set_xscale('linear')
  2111. ax.get_figure(root=True).canvas.draw_idle()
  2112. elif scalex == 'linear':
  2113. try:
  2114. ax.set_xscale('log')
  2115. except ValueError as exc:
  2116. _log.warning(str(exc))
  2117. ax.set_xscale('linear')
  2118. ax.get_figure(root=True).canvas.draw_idle()
  2119. def button_press_handler(event, canvas=None, toolbar=None):
  2120. """
  2121. The default Matplotlib button actions for extra mouse buttons.
  2122. Parameters are as for `key_press_handler`, except that *event* is a
  2123. `MouseEvent`.
  2124. """
  2125. if canvas is None:
  2126. canvas = event.canvas
  2127. if toolbar is None:
  2128. toolbar = canvas.toolbar
  2129. if toolbar is not None:
  2130. button_name = str(MouseButton(event.button))
  2131. if button_name in rcParams['keymap.back']:
  2132. toolbar.back()
  2133. elif button_name in rcParams['keymap.forward']:
  2134. toolbar.forward()
  2135. class NonGuiException(Exception):
  2136. """Raised when trying show a figure in a non-GUI backend."""
  2137. pass
  2138. class FigureManagerBase:
  2139. """
  2140. A backend-independent abstraction of a figure container and controller.
  2141. The figure manager is used by pyplot to interact with the window in a
  2142. backend-independent way. It's an adapter for the real (GUI) framework that
  2143. represents the visual figure on screen.
  2144. The figure manager is connected to a specific canvas instance, which in turn
  2145. is connected to a specific figure instance. To access a figure manager for
  2146. a given figure in user code, you typically use ``fig.canvas.manager``.
  2147. GUI backends derive from this class to translate common operations such
  2148. as *show* or *resize* to the GUI-specific code. Non-GUI backends do not
  2149. support these operations and can just use the base class.
  2150. This following basic operations are accessible:
  2151. **Window operations**
  2152. - `~.FigureManagerBase.show`
  2153. - `~.FigureManagerBase.destroy`
  2154. - `~.FigureManagerBase.full_screen_toggle`
  2155. - `~.FigureManagerBase.resize`
  2156. - `~.FigureManagerBase.get_window_title`
  2157. - `~.FigureManagerBase.set_window_title`
  2158. **Key and mouse button press handling**
  2159. The figure manager sets up default key and mouse button press handling by
  2160. hooking up the `.key_press_handler` to the matplotlib event system. This
  2161. ensures the same shortcuts and mouse actions across backends.
  2162. **Other operations**
  2163. Subclasses will have additional attributes and functions to access
  2164. additional functionality. This is of course backend-specific. For example,
  2165. most GUI backends have ``window`` and ``toolbar`` attributes that give
  2166. access to the native GUI widgets of the respective framework.
  2167. Attributes
  2168. ----------
  2169. canvas : `FigureCanvasBase`
  2170. The backend-specific canvas instance.
  2171. num : int or str
  2172. The figure number.
  2173. key_press_handler_id : int
  2174. The default key handler cid, when using the toolmanager.
  2175. To disable the default key press handling use::
  2176. figure.canvas.mpl_disconnect(
  2177. figure.canvas.manager.key_press_handler_id)
  2178. button_press_handler_id : int
  2179. The default mouse button handler cid, when using the toolmanager.
  2180. To disable the default button press handling use::
  2181. figure.canvas.mpl_disconnect(
  2182. figure.canvas.manager.button_press_handler_id)
  2183. """
  2184. _toolbar2_class = None
  2185. _toolmanager_toolbar_class = None
  2186. def __init__(self, canvas, num):
  2187. self.canvas = canvas
  2188. canvas.manager = self # store a pointer to parent
  2189. self.num = num
  2190. self.set_window_title(f"Figure {num:d}")
  2191. self.key_press_handler_id = None
  2192. self.button_press_handler_id = None
  2193. if rcParams['toolbar'] != 'toolmanager':
  2194. self.key_press_handler_id = self.canvas.mpl_connect(
  2195. 'key_press_event', key_press_handler)
  2196. self.button_press_handler_id = self.canvas.mpl_connect(
  2197. 'button_press_event', button_press_handler)
  2198. self.toolmanager = (ToolManager(canvas.figure)
  2199. if mpl.rcParams['toolbar'] == 'toolmanager'
  2200. else None)
  2201. if (mpl.rcParams["toolbar"] == "toolbar2"
  2202. and self._toolbar2_class):
  2203. self.toolbar = self._toolbar2_class(self.canvas)
  2204. elif (mpl.rcParams["toolbar"] == "toolmanager"
  2205. and self._toolmanager_toolbar_class):
  2206. self.toolbar = self._toolmanager_toolbar_class(self.toolmanager)
  2207. else:
  2208. self.toolbar = None
  2209. if self.toolmanager:
  2210. tools.add_tools_to_manager(self.toolmanager)
  2211. if self.toolbar:
  2212. tools.add_tools_to_container(self.toolbar)
  2213. @self.canvas.figure.add_axobserver
  2214. def notify_axes_change(fig):
  2215. # Called whenever the current Axes is changed.
  2216. if self.toolmanager is None and self.toolbar is not None:
  2217. self.toolbar.update()
  2218. @classmethod
  2219. def create_with_canvas(cls, canvas_class, figure, num):
  2220. """
  2221. Create a manager for a given *figure* using a specific *canvas_class*.
  2222. Backends should override this method if they have specific needs for
  2223. setting up the canvas or the manager.
  2224. """
  2225. return cls(canvas_class(figure), num)
  2226. @classmethod
  2227. def start_main_loop(cls):
  2228. """
  2229. Start the main event loop.
  2230. This method is called by `.FigureManagerBase.pyplot_show`, which is the
  2231. implementation of `.pyplot.show`. To customize the behavior of
  2232. `.pyplot.show`, interactive backends should usually override
  2233. `~.FigureManagerBase.start_main_loop`; if more customized logic is
  2234. necessary, `~.FigureManagerBase.pyplot_show` can also be overridden.
  2235. """
  2236. @classmethod
  2237. def pyplot_show(cls, *, block=None):
  2238. """
  2239. Show all figures. This method is the implementation of `.pyplot.show`.
  2240. To customize the behavior of `.pyplot.show`, interactive backends
  2241. should usually override `~.FigureManagerBase.start_main_loop`; if more
  2242. customized logic is necessary, `~.FigureManagerBase.pyplot_show` can
  2243. also be overridden.
  2244. Parameters
  2245. ----------
  2246. block : bool, optional
  2247. Whether to block by calling ``start_main_loop``. The default,
  2248. None, means to block if we are neither in IPython's ``%pylab`` mode
  2249. nor in ``interactive`` mode.
  2250. """
  2251. managers = Gcf.get_all_fig_managers()
  2252. if not managers:
  2253. return
  2254. for manager in managers:
  2255. try:
  2256. manager.show() # Emits a warning for non-interactive backend.
  2257. except NonGuiException as exc:
  2258. _api.warn_external(str(exc))
  2259. if block is None:
  2260. # Hack: Are we in IPython's %pylab mode? In pylab mode, IPython
  2261. # (>= 0.10) tacks a _needmain attribute onto pyplot.show (always
  2262. # set to False).
  2263. pyplot_show = getattr(sys.modules.get("matplotlib.pyplot"), "show", None)
  2264. ipython_pylab = hasattr(pyplot_show, "_needmain")
  2265. block = not ipython_pylab and not is_interactive()
  2266. if block:
  2267. cls.start_main_loop()
  2268. def show(self):
  2269. """
  2270. For GUI backends, show the figure window and redraw.
  2271. For non-GUI backends, raise an exception, unless running headless (i.e.
  2272. on Linux with an unset DISPLAY); this exception is converted to a
  2273. warning in `.Figure.show`.
  2274. """
  2275. # This should be overridden in GUI backends.
  2276. if sys.platform == "linux" and not os.environ.get("DISPLAY"):
  2277. # We cannot check _get_running_interactive_framework() ==
  2278. # "headless" because that would also suppress the warning when
  2279. # $DISPLAY exists but is invalid, which is more likely an error and
  2280. # thus warrants a warning.
  2281. return
  2282. raise NonGuiException(
  2283. f"{type(self.canvas).__name__} is non-interactive, and thus cannot be "
  2284. f"shown")
  2285. def destroy(self):
  2286. pass
  2287. def full_screen_toggle(self):
  2288. pass
  2289. def resize(self, w, h):
  2290. """For GUI backends, resize the window (in physical pixels)."""
  2291. def get_window_title(self):
  2292. """Return the title text of the window containing the figure."""
  2293. return self._window_title
  2294. def set_window_title(self, title):
  2295. """
  2296. Set the title text of the window containing the figure.
  2297. Examples
  2298. --------
  2299. >>> fig = plt.figure()
  2300. >>> fig.canvas.manager.set_window_title('My figure')
  2301. """
  2302. # This attribute is not defined in __init__ (but __init__ calls this
  2303. # setter), as derived classes (real GUI managers) will store this
  2304. # information directly on the widget; only the base (non-GUI) manager
  2305. # class needs a specific attribute for it (so that filename escaping
  2306. # can be checked in the test suite).
  2307. self._window_title = title
  2308. cursors = tools.cursors
  2309. class _Mode(str, Enum):
  2310. NONE = ""
  2311. PAN = "pan/zoom"
  2312. ZOOM = "zoom rect"
  2313. def __str__(self):
  2314. return self.value
  2315. @property
  2316. def _navigate_mode(self):
  2317. return self.name if self is not _Mode.NONE else None
  2318. class NavigationToolbar2:
  2319. """
  2320. Base class for the navigation cursor, version 2.
  2321. Backends must implement a canvas that handles connections for
  2322. 'button_press_event' and 'button_release_event'. See
  2323. :meth:`FigureCanvasBase.mpl_connect` for more information.
  2324. They must also define
  2325. :meth:`save_figure`
  2326. Save the current figure.
  2327. :meth:`draw_rubberband` (optional)
  2328. Draw the zoom to rect "rubberband" rectangle.
  2329. :meth:`set_message` (optional)
  2330. Display message.
  2331. :meth:`set_history_buttons` (optional)
  2332. You can change the history back / forward buttons to indicate disabled / enabled
  2333. state.
  2334. and override ``__init__`` to set up the toolbar -- without forgetting to
  2335. call the base-class init. Typically, ``__init__`` needs to set up toolbar
  2336. buttons connected to the `home`, `back`, `forward`, `pan`, `zoom`, and
  2337. `save_figure` methods and using standard icons in the "images" subdirectory
  2338. of the data path.
  2339. That's it, we'll do the rest!
  2340. """
  2341. # list of toolitems to add to the toolbar, format is:
  2342. # (
  2343. # text, # the text of the button (often not visible to users)
  2344. # tooltip_text, # the tooltip shown on hover (where possible)
  2345. # image_file, # name of the image for the button (without the extension)
  2346. # name_of_method, # name of the method in NavigationToolbar2 to call
  2347. # )
  2348. toolitems = (
  2349. ('Home', 'Reset original view', 'home', 'home'),
  2350. ('Back', 'Back to previous view', 'back', 'back'),
  2351. ('Forward', 'Forward to next view', 'forward', 'forward'),
  2352. (None, None, None, None),
  2353. ('Pan',
  2354. 'Left button pans, Right button zooms\n'
  2355. 'x/y fixes axis, CTRL fixes aspect',
  2356. 'move', 'pan'),
  2357. ('Zoom', 'Zoom to rectangle\nx/y fixes axis', 'zoom_to_rect', 'zoom'),
  2358. ('Subplots', 'Configure subplots', 'subplots', 'configure_subplots'),
  2359. (None, None, None, None),
  2360. ('Save', 'Save the figure', 'filesave', 'save_figure'),
  2361. )
  2362. UNKNOWN_SAVED_STATUS = object()
  2363. def __init__(self, canvas):
  2364. self.canvas = canvas
  2365. canvas.toolbar = self
  2366. self._nav_stack = cbook._Stack()
  2367. # This cursor will be set after the initial draw.
  2368. self._last_cursor = tools.Cursors.POINTER
  2369. self._id_press = self.canvas.mpl_connect(
  2370. 'button_press_event', self._zoom_pan_handler)
  2371. self._id_release = self.canvas.mpl_connect(
  2372. 'button_release_event', self._zoom_pan_handler)
  2373. self._id_drag = self.canvas.mpl_connect(
  2374. 'motion_notify_event', self.mouse_move)
  2375. self._pan_info = None
  2376. self._zoom_info = None
  2377. self.mode = _Mode.NONE # a mode string for the status bar
  2378. self.set_history_buttons()
  2379. def set_message(self, s):
  2380. """Display a message on toolbar or in status bar."""
  2381. def draw_rubberband(self, event, x0, y0, x1, y1):
  2382. """
  2383. Draw a rectangle rubberband to indicate zoom limits.
  2384. Note that it is not guaranteed that ``x0 <= x1`` and ``y0 <= y1``.
  2385. """
  2386. def remove_rubberband(self):
  2387. """Remove the rubberband."""
  2388. def home(self, *args):
  2389. """
  2390. Restore the original view.
  2391. For convenience of being directly connected as a GUI callback, which
  2392. often get passed additional parameters, this method accepts arbitrary
  2393. parameters, but does not use them.
  2394. """
  2395. self._nav_stack.home()
  2396. self.set_history_buttons()
  2397. self._update_view()
  2398. def back(self, *args):
  2399. """
  2400. Move back up the view lim stack.
  2401. For convenience of being directly connected as a GUI callback, which
  2402. often get passed additional parameters, this method accepts arbitrary
  2403. parameters, but does not use them.
  2404. """
  2405. self._nav_stack.back()
  2406. self.set_history_buttons()
  2407. self._update_view()
  2408. def forward(self, *args):
  2409. """
  2410. Move forward in the view lim stack.
  2411. For convenience of being directly connected as a GUI callback, which
  2412. often get passed additional parameters, this method accepts arbitrary
  2413. parameters, but does not use them.
  2414. """
  2415. self._nav_stack.forward()
  2416. self.set_history_buttons()
  2417. self._update_view()
  2418. def _update_cursor(self, event):
  2419. """
  2420. Update the cursor after a mouse move event or a tool (de)activation.
  2421. """
  2422. if self.mode and event.inaxes and event.inaxes.get_navigate():
  2423. if (self.mode == _Mode.ZOOM
  2424. and self._last_cursor != tools.Cursors.SELECT_REGION):
  2425. self.canvas.set_cursor(tools.Cursors.SELECT_REGION)
  2426. self._last_cursor = tools.Cursors.SELECT_REGION
  2427. elif (self.mode == _Mode.PAN
  2428. and self._last_cursor != tools.Cursors.MOVE):
  2429. self.canvas.set_cursor(tools.Cursors.MOVE)
  2430. self._last_cursor = tools.Cursors.MOVE
  2431. elif self._last_cursor != tools.Cursors.POINTER:
  2432. self.canvas.set_cursor(tools.Cursors.POINTER)
  2433. self._last_cursor = tools.Cursors.POINTER
  2434. @contextmanager
  2435. def _wait_cursor_for_draw_cm(self):
  2436. """
  2437. Set the cursor to a wait cursor when drawing the canvas.
  2438. In order to avoid constantly changing the cursor when the canvas
  2439. changes frequently, do nothing if this context was triggered during the
  2440. last second. (Optimally we'd prefer only setting the wait cursor if
  2441. the *current* draw takes too long, but the current draw blocks the GUI
  2442. thread).
  2443. """
  2444. self._draw_time, last_draw_time = (
  2445. time.time(), getattr(self, "_draw_time", -np.inf))
  2446. if self._draw_time - last_draw_time > 1:
  2447. try:
  2448. self.canvas.set_cursor(tools.Cursors.WAIT)
  2449. yield
  2450. finally:
  2451. self.canvas.set_cursor(self._last_cursor)
  2452. else:
  2453. yield
  2454. @staticmethod
  2455. def _mouse_event_to_message(event):
  2456. if event.inaxes and event.inaxes.get_navigate():
  2457. try:
  2458. s = event.inaxes.format_coord(event.xdata, event.ydata)
  2459. except (ValueError, OverflowError):
  2460. pass
  2461. else:
  2462. s = s.rstrip()
  2463. artists = [a for a in event.inaxes._mouseover_set
  2464. if a.contains(event)[0] and a.get_visible()]
  2465. if artists:
  2466. a = cbook._topmost_artist(artists)
  2467. if a is not event.inaxes.patch:
  2468. data = a.get_cursor_data(event)
  2469. if data is not None:
  2470. data_str = a.format_cursor_data(data).rstrip()
  2471. if data_str:
  2472. s = s + '\n' + data_str
  2473. return s
  2474. return ""
  2475. def mouse_move(self, event):
  2476. self._update_cursor(event)
  2477. self.set_message(self._mouse_event_to_message(event))
  2478. def _zoom_pan_handler(self, event):
  2479. if self.mode == _Mode.PAN:
  2480. if event.name == "button_press_event":
  2481. self.press_pan(event)
  2482. elif event.name == "button_release_event":
  2483. self.release_pan(event)
  2484. if self.mode == _Mode.ZOOM:
  2485. if event.name == "button_press_event":
  2486. self.press_zoom(event)
  2487. elif event.name == "button_release_event":
  2488. self.release_zoom(event)
  2489. def _start_event_axes_interaction(self, event, *, method):
  2490. def _ax_filter(ax):
  2491. return (ax.in_axes(event) and
  2492. ax.get_navigate() and
  2493. getattr(ax, f"can_{method}")()
  2494. )
  2495. def _capture_events(ax):
  2496. f = ax.get_forward_navigation_events()
  2497. if f == "auto": # (capture = patch visibility)
  2498. f = not ax.patch.get_visible()
  2499. return not f
  2500. # get all relevant axes for the event
  2501. axes = list(filter(_ax_filter, self.canvas.figure.get_axes()))
  2502. if len(axes) == 0:
  2503. return []
  2504. if self._nav_stack() is None:
  2505. self.push_current() # Set the home button to this view.
  2506. # group axes by zorder (reverse to trigger later axes first)
  2507. grps = dict()
  2508. for ax in reversed(axes):
  2509. grps.setdefault(ax.get_zorder(), []).append(ax)
  2510. axes_to_trigger = []
  2511. # go through zorders in reverse until we hit a capturing axes
  2512. for zorder in sorted(grps, reverse=True):
  2513. for ax in grps[zorder]:
  2514. axes_to_trigger.append(ax)
  2515. # NOTE: shared axes are automatically triggered, but twin-axes not!
  2516. axes_to_trigger.extend(ax._twinned_axes.get_siblings(ax))
  2517. if _capture_events(ax):
  2518. break # break if we hit a capturing axes
  2519. else:
  2520. # If the inner loop finished without an explicit break,
  2521. # (e.g. no capturing axes was found) continue the
  2522. # outer loop to the next zorder.
  2523. continue
  2524. # If the inner loop was terminated with an explicit break,
  2525. # terminate the outer loop as well.
  2526. break
  2527. # avoid duplicated triggers (but keep order of list)
  2528. axes_to_trigger = list(dict.fromkeys(axes_to_trigger))
  2529. return axes_to_trigger
  2530. def pan(self, *args):
  2531. """
  2532. Toggle the pan/zoom tool.
  2533. Pan with left button, zoom with right.
  2534. """
  2535. if not self.canvas.widgetlock.available(self):
  2536. self.set_message("pan unavailable")
  2537. return
  2538. if self.mode == _Mode.PAN:
  2539. self.mode = _Mode.NONE
  2540. self.canvas.widgetlock.release(self)
  2541. else:
  2542. self.mode = _Mode.PAN
  2543. self.canvas.widgetlock(self)
  2544. for a in self.canvas.figure.get_axes():
  2545. a.set_navigate_mode(self.mode._navigate_mode)
  2546. _PanInfo = namedtuple("_PanInfo", "button axes cid")
  2547. def press_pan(self, event):
  2548. """Callback for mouse button press in pan/zoom mode."""
  2549. if (event.button not in [MouseButton.LEFT, MouseButton.RIGHT]
  2550. or event.x is None or event.y is None):
  2551. return
  2552. axes = self._start_event_axes_interaction(event, method="pan")
  2553. if not axes:
  2554. return
  2555. # call "ax.start_pan(..)" on all relevant axes of an event
  2556. for ax in axes:
  2557. ax.start_pan(event.x, event.y, event.button)
  2558. self.canvas.mpl_disconnect(self._id_drag)
  2559. id_drag = self.canvas.mpl_connect("motion_notify_event", self.drag_pan)
  2560. self._pan_info = self._PanInfo(
  2561. button=event.button, axes=axes, cid=id_drag)
  2562. def drag_pan(self, event):
  2563. """Callback for dragging in pan/zoom mode."""
  2564. for ax in self._pan_info.axes:
  2565. # Using the recorded button at the press is safer than the current
  2566. # button, as multiple buttons can get pressed during motion.
  2567. ax.drag_pan(self._pan_info.button, event.key, event.x, event.y)
  2568. self.canvas.draw_idle()
  2569. def release_pan(self, event):
  2570. """Callback for mouse button release in pan/zoom mode."""
  2571. if self._pan_info is None:
  2572. return
  2573. self.canvas.mpl_disconnect(self._pan_info.cid)
  2574. self._id_drag = self.canvas.mpl_connect(
  2575. 'motion_notify_event', self.mouse_move)
  2576. for ax in self._pan_info.axes:
  2577. ax.end_pan()
  2578. self.canvas.draw_idle()
  2579. self._pan_info = None
  2580. self.push_current()
  2581. def zoom(self, *args):
  2582. if not self.canvas.widgetlock.available(self):
  2583. self.set_message("zoom unavailable")
  2584. return
  2585. """Toggle zoom to rect mode."""
  2586. if self.mode == _Mode.ZOOM:
  2587. self.mode = _Mode.NONE
  2588. self.canvas.widgetlock.release(self)
  2589. else:
  2590. self.mode = _Mode.ZOOM
  2591. self.canvas.widgetlock(self)
  2592. for a in self.canvas.figure.get_axes():
  2593. a.set_navigate_mode(self.mode._navigate_mode)
  2594. _ZoomInfo = namedtuple("_ZoomInfo", "direction start_xy axes cid cbar")
  2595. def press_zoom(self, event):
  2596. """Callback for mouse button press in zoom to rect mode."""
  2597. if (event.button not in [MouseButton.LEFT, MouseButton.RIGHT]
  2598. or event.x is None or event.y is None):
  2599. return
  2600. axes = self._start_event_axes_interaction(event, method="zoom")
  2601. if not axes:
  2602. return
  2603. id_zoom = self.canvas.mpl_connect(
  2604. "motion_notify_event", self.drag_zoom)
  2605. # A colorbar is one-dimensional, so we extend the zoom rectangle out
  2606. # to the edge of the Axes bbox in the other dimension. To do that we
  2607. # store the orientation of the colorbar for later.
  2608. parent_ax = axes[0]
  2609. if hasattr(parent_ax, "_colorbar"):
  2610. cbar = parent_ax._colorbar.orientation
  2611. else:
  2612. cbar = None
  2613. self._zoom_info = self._ZoomInfo(
  2614. direction="in" if event.button == 1 else "out",
  2615. start_xy=(event.x, event.y), axes=axes, cid=id_zoom, cbar=cbar)
  2616. def drag_zoom(self, event):
  2617. """Callback for dragging in zoom mode."""
  2618. start_xy = self._zoom_info.start_xy
  2619. ax = self._zoom_info.axes[0]
  2620. (x1, y1), (x2, y2) = np.clip(
  2621. [start_xy, [event.x, event.y]], ax.bbox.min, ax.bbox.max)
  2622. key = event.key
  2623. # Force the key on colorbars to extend the short-axis bbox
  2624. if self._zoom_info.cbar == "horizontal":
  2625. key = "x"
  2626. elif self._zoom_info.cbar == "vertical":
  2627. key = "y"
  2628. if key == "x":
  2629. y1, y2 = ax.bbox.intervaly
  2630. elif key == "y":
  2631. x1, x2 = ax.bbox.intervalx
  2632. self.draw_rubberband(event, x1, y1, x2, y2)
  2633. def release_zoom(self, event):
  2634. """Callback for mouse button release in zoom to rect mode."""
  2635. if self._zoom_info is None:
  2636. return
  2637. # We don't check the event button here, so that zooms can be cancelled
  2638. # by (pressing and) releasing another mouse button.
  2639. self.canvas.mpl_disconnect(self._zoom_info.cid)
  2640. self.remove_rubberband()
  2641. start_x, start_y = self._zoom_info.start_xy
  2642. key = event.key
  2643. # Force the key on colorbars to ignore the zoom-cancel on the
  2644. # short-axis side
  2645. if self._zoom_info.cbar == "horizontal":
  2646. key = "x"
  2647. elif self._zoom_info.cbar == "vertical":
  2648. key = "y"
  2649. # Ignore single clicks: 5 pixels is a threshold that allows the user to
  2650. # "cancel" a zoom action by zooming by less than 5 pixels.
  2651. if ((abs(event.x - start_x) < 5 and key != "y") or
  2652. (abs(event.y - start_y) < 5 and key != "x")):
  2653. self.canvas.draw_idle()
  2654. self._zoom_info = None
  2655. return
  2656. for i, ax in enumerate(self._zoom_info.axes):
  2657. # Detect whether this Axes is twinned with an earlier Axes in the
  2658. # list of zoomed Axes, to avoid double zooming.
  2659. twinx = any(ax.get_shared_x_axes().joined(ax, prev)
  2660. for prev in self._zoom_info.axes[:i])
  2661. twiny = any(ax.get_shared_y_axes().joined(ax, prev)
  2662. for prev in self._zoom_info.axes[:i])
  2663. ax._set_view_from_bbox(
  2664. (start_x, start_y, event.x, event.y),
  2665. self._zoom_info.direction, key, twinx, twiny)
  2666. self.canvas.draw_idle()
  2667. self._zoom_info = None
  2668. self.push_current()
  2669. def push_current(self):
  2670. """Push the current view limits and position onto the stack."""
  2671. self._nav_stack.push(
  2672. WeakKeyDictionary(
  2673. {ax: (ax._get_view(),
  2674. # Store both the original and modified positions.
  2675. (ax.get_position(True).frozen(),
  2676. ax.get_position().frozen()))
  2677. for ax in self.canvas.figure.axes}))
  2678. self.set_history_buttons()
  2679. def _update_view(self):
  2680. """
  2681. Update the viewlim and position from the view and position stack for
  2682. each Axes.
  2683. """
  2684. nav_info = self._nav_stack()
  2685. if nav_info is None:
  2686. return
  2687. # Retrieve all items at once to avoid any risk of GC deleting an Axes
  2688. # while in the middle of the loop below.
  2689. items = list(nav_info.items())
  2690. for ax, (view, (pos_orig, pos_active)) in items:
  2691. ax._set_view(view)
  2692. # Restore both the original and modified positions
  2693. ax._set_position(pos_orig, 'original')
  2694. ax._set_position(pos_active, 'active')
  2695. self.canvas.draw_idle()
  2696. def configure_subplots(self, *args):
  2697. if hasattr(self, "subplot_tool"):
  2698. self.subplot_tool.figure.canvas.manager.show()
  2699. return
  2700. # This import needs to happen here due to circular imports.
  2701. from matplotlib.figure import Figure
  2702. with mpl.rc_context({"toolbar": "none"}): # No navbar for the toolfig.
  2703. manager = type(self.canvas).new_manager(Figure(figsize=(6, 3)), -1)
  2704. manager.set_window_title("Subplot configuration tool")
  2705. tool_fig = manager.canvas.figure
  2706. tool_fig.subplots_adjust(top=0.9)
  2707. self.subplot_tool = widgets.SubplotTool(self.canvas.figure, tool_fig)
  2708. cid = self.canvas.mpl_connect(
  2709. "close_event", lambda e: manager.destroy())
  2710. def on_tool_fig_close(e):
  2711. self.canvas.mpl_disconnect(cid)
  2712. del self.subplot_tool
  2713. tool_fig.canvas.mpl_connect("close_event", on_tool_fig_close)
  2714. manager.show()
  2715. return self.subplot_tool
  2716. def save_figure(self, *args):
  2717. """
  2718. Save the current figure.
  2719. Backend implementations may choose to return
  2720. the absolute path of the saved file, if any, as
  2721. a string.
  2722. If no file is created then `None` is returned.
  2723. If the backend does not implement this functionality
  2724. then `NavigationToolbar2.UNKNOWN_SAVED_STATUS` is returned.
  2725. Returns
  2726. -------
  2727. str or `NavigationToolbar2.UNKNOWN_SAVED_STATUS` or `None`
  2728. The filepath of the saved figure.
  2729. Returns `None` if figure is not saved.
  2730. Returns `NavigationToolbar2.UNKNOWN_SAVED_STATUS` when
  2731. the backend does not provide the information.
  2732. """
  2733. raise NotImplementedError
  2734. def update(self):
  2735. """Reset the Axes stack."""
  2736. self._nav_stack.clear()
  2737. self.set_history_buttons()
  2738. def set_history_buttons(self):
  2739. """Enable or disable the back/forward button."""
  2740. class ToolContainerBase:
  2741. """
  2742. Base class for all tool containers, e.g. toolbars.
  2743. Attributes
  2744. ----------
  2745. toolmanager : `.ToolManager`
  2746. The tools with which this `ToolContainer` wants to communicate.
  2747. """
  2748. _icon_extension = '.png'
  2749. """
  2750. Toolcontainer button icon image format extension
  2751. **String**: Image extension
  2752. """
  2753. def __init__(self, toolmanager):
  2754. self.toolmanager = toolmanager
  2755. toolmanager.toolmanager_connect(
  2756. 'tool_message_event',
  2757. lambda event: self.set_message(event.message))
  2758. toolmanager.toolmanager_connect(
  2759. 'tool_removed_event',
  2760. lambda event: self.remove_toolitem(event.tool.name))
  2761. def _tool_toggled_cbk(self, event):
  2762. """
  2763. Capture the 'tool_trigger_[name]'
  2764. This only gets used for toggled tools.
  2765. """
  2766. self.toggle_toolitem(event.tool.name, event.tool.toggled)
  2767. def add_tool(self, tool, group, position=-1):
  2768. """
  2769. Add a tool to this container.
  2770. Parameters
  2771. ----------
  2772. tool : tool_like
  2773. The tool to add, see `.ToolManager.get_tool`.
  2774. group : str
  2775. The name of the group to add this tool to.
  2776. position : int, default: -1
  2777. The position within the group to place this tool.
  2778. """
  2779. tool = self.toolmanager.get_tool(tool)
  2780. image = self._get_image_filename(tool)
  2781. toggle = getattr(tool, 'toggled', None) is not None
  2782. self.add_toolitem(tool.name, group, position,
  2783. image, tool.description, toggle)
  2784. if toggle:
  2785. self.toolmanager.toolmanager_connect('tool_trigger_%s' % tool.name,
  2786. self._tool_toggled_cbk)
  2787. # If initially toggled
  2788. if tool.toggled:
  2789. self.toggle_toolitem(tool.name, True)
  2790. def _get_image_filename(self, tool):
  2791. """Resolve a tool icon's filename."""
  2792. if not tool.image:
  2793. return None
  2794. if os.path.isabs(tool.image):
  2795. filename = tool.image
  2796. else:
  2797. if "image" in getattr(tool, "__dict__", {}):
  2798. raise ValueError("If 'tool.image' is an instance variable, "
  2799. "it must be an absolute path")
  2800. for cls in type(tool).__mro__:
  2801. if "image" in vars(cls):
  2802. try:
  2803. src = inspect.getfile(cls)
  2804. break
  2805. except (OSError, TypeError):
  2806. raise ValueError("Failed to locate source file "
  2807. "where 'tool.image' is defined") from None
  2808. else:
  2809. raise ValueError("Failed to find parent class defining 'tool.image'")
  2810. filename = str(pathlib.Path(src).parent / tool.image)
  2811. for filename in [filename, filename + self._icon_extension]:
  2812. if os.path.isfile(filename):
  2813. return os.path.abspath(filename)
  2814. for fname in [ # Fallback; once deprecation elapses.
  2815. tool.image,
  2816. tool.image + self._icon_extension,
  2817. cbook._get_data_path("images", tool.image),
  2818. cbook._get_data_path("images", tool.image + self._icon_extension),
  2819. ]:
  2820. if os.path.isfile(fname):
  2821. _api.warn_deprecated(
  2822. "3.9", message=f"Loading icon {tool.image!r} from the current "
  2823. "directory or from Matplotlib's image directory. This behavior "
  2824. "is deprecated since %(since)s and will be removed in %(removal)s; "
  2825. "Tool.image should be set to a path relative to the Tool's source "
  2826. "file, or to an absolute path.")
  2827. return os.path.abspath(fname)
  2828. def trigger_tool(self, name):
  2829. """
  2830. Trigger the tool.
  2831. Parameters
  2832. ----------
  2833. name : str
  2834. Name (id) of the tool triggered from within the container.
  2835. """
  2836. self.toolmanager.trigger_tool(name, sender=self)
  2837. def add_toolitem(self, name, group, position, image, description, toggle):
  2838. """
  2839. A hook to add a toolitem to the container.
  2840. This hook must be implemented in each backend and contains the
  2841. backend-specific code to add an element to the toolbar.
  2842. .. warning::
  2843. This is part of the backend implementation and should
  2844. not be called by end-users. They should instead call
  2845. `.ToolContainerBase.add_tool`.
  2846. The callback associated with the button click event
  2847. must be *exactly* ``self.trigger_tool(name)``.
  2848. Parameters
  2849. ----------
  2850. name : str
  2851. Name of the tool to add, this gets used as the tool's ID and as the
  2852. default label of the buttons.
  2853. group : str
  2854. Name of the group that this tool belongs to.
  2855. position : int
  2856. Position of the tool within its group, if -1 it goes at the end.
  2857. image : str
  2858. Filename of the image for the button or `None`.
  2859. description : str
  2860. Description of the tool, used for the tooltips.
  2861. toggle : bool
  2862. * `True` : The button is a toggle (change the pressed/unpressed
  2863. state between consecutive clicks).
  2864. * `False` : The button is a normal button (returns to unpressed
  2865. state after release).
  2866. """
  2867. raise NotImplementedError
  2868. def toggle_toolitem(self, name, toggled):
  2869. """
  2870. A hook to toggle a toolitem without firing an event.
  2871. This hook must be implemented in each backend and contains the
  2872. backend-specific code to silently toggle a toolbar element.
  2873. .. warning::
  2874. This is part of the backend implementation and should
  2875. not be called by end-users. They should instead call
  2876. `.ToolManager.trigger_tool` or `.ToolContainerBase.trigger_tool`
  2877. (which are equivalent).
  2878. Parameters
  2879. ----------
  2880. name : str
  2881. Id of the tool to toggle.
  2882. toggled : bool
  2883. Whether to set this tool as toggled or not.
  2884. """
  2885. raise NotImplementedError
  2886. def remove_toolitem(self, name):
  2887. """
  2888. A hook to remove a toolitem from the container.
  2889. This hook must be implemented in each backend and contains the
  2890. backend-specific code to remove an element from the toolbar; it is
  2891. called when `.ToolManager` emits a ``tool_removed_event``.
  2892. Because some tools are present only on the `.ToolManager` but not on
  2893. the `ToolContainer`, this method must be a no-op when called on a tool
  2894. absent from the container.
  2895. .. warning::
  2896. This is part of the backend implementation and should
  2897. not be called by end-users. They should instead call
  2898. `.ToolManager.remove_tool`.
  2899. Parameters
  2900. ----------
  2901. name : str
  2902. Name of the tool to remove.
  2903. """
  2904. raise NotImplementedError
  2905. def set_message(self, s):
  2906. """
  2907. Display a message on the toolbar.
  2908. Parameters
  2909. ----------
  2910. s : str
  2911. Message text.
  2912. """
  2913. raise NotImplementedError
  2914. class _Backend:
  2915. # A backend can be defined by using the following pattern:
  2916. #
  2917. # @_Backend.export
  2918. # class FooBackend(_Backend):
  2919. # # override the attributes and methods documented below.
  2920. # `backend_version` may be overridden by the subclass.
  2921. backend_version = "unknown"
  2922. # The `FigureCanvas` class must be defined.
  2923. FigureCanvas = None
  2924. # For interactive backends, the `FigureManager` class must be overridden.
  2925. FigureManager = FigureManagerBase
  2926. # For interactive backends, `mainloop` should be a function taking no
  2927. # argument and starting the backend main loop. It should be left as None
  2928. # for non-interactive backends.
  2929. mainloop = None
  2930. # The following methods will be automatically defined and exported, but
  2931. # can be overridden.
  2932. @classmethod
  2933. def new_figure_manager(cls, num, *args, **kwargs):
  2934. """Create a new figure manager instance."""
  2935. # This import needs to happen here due to circular imports.
  2936. from matplotlib.figure import Figure
  2937. fig_cls = kwargs.pop('FigureClass', Figure)
  2938. fig = fig_cls(*args, **kwargs)
  2939. return cls.new_figure_manager_given_figure(num, fig)
  2940. @classmethod
  2941. def new_figure_manager_given_figure(cls, num, figure):
  2942. """Create a new figure manager instance for the given figure."""
  2943. return cls.FigureCanvas.new_manager(figure, num)
  2944. @classmethod
  2945. def draw_if_interactive(cls):
  2946. manager_class = cls.FigureCanvas.manager_class
  2947. # Interactive backends reimplement start_main_loop or pyplot_show.
  2948. backend_is_interactive = (
  2949. manager_class.start_main_loop != FigureManagerBase.start_main_loop
  2950. or manager_class.pyplot_show != FigureManagerBase.pyplot_show)
  2951. if backend_is_interactive and is_interactive():
  2952. manager = Gcf.get_active()
  2953. if manager:
  2954. manager.canvas.draw_idle()
  2955. @classmethod
  2956. def show(cls, *, block=None):
  2957. """
  2958. Show all figures.
  2959. `show` blocks by calling `mainloop` if *block* is ``True``, or if it is
  2960. ``None`` and we are not in `interactive` mode and if IPython's
  2961. ``%matplotlib`` integration has not been activated.
  2962. """
  2963. managers = Gcf.get_all_fig_managers()
  2964. if not managers:
  2965. return
  2966. for manager in managers:
  2967. try:
  2968. manager.show() # Emits a warning for non-interactive backend.
  2969. except NonGuiException as exc:
  2970. _api.warn_external(str(exc))
  2971. if cls.mainloop is None:
  2972. return
  2973. if block is None:
  2974. # Hack: Is IPython's %matplotlib integration activated? If so,
  2975. # IPython's activate_matplotlib (>= 0.10) tacks a _needmain
  2976. # attribute onto pyplot.show (always set to False).
  2977. pyplot_show = getattr(sys.modules.get("matplotlib.pyplot"), "show", None)
  2978. ipython_pylab = hasattr(pyplot_show, "_needmain")
  2979. block = not ipython_pylab and not is_interactive()
  2980. if block:
  2981. cls.mainloop()
  2982. # This method is the one actually exporting the required methods.
  2983. @staticmethod
  2984. def export(cls):
  2985. for name in [
  2986. "backend_version",
  2987. "FigureCanvas",
  2988. "FigureManager",
  2989. "new_figure_manager",
  2990. "new_figure_manager_given_figure",
  2991. "draw_if_interactive",
  2992. "show",
  2993. ]:
  2994. setattr(sys.modules[cls.__module__], name, getattr(cls, name))
  2995. # For back-compatibility, generate a shim `Show` class.
  2996. class Show(ShowBase):
  2997. def mainloop(self):
  2998. return cls.mainloop()
  2999. setattr(sys.modules[cls.__module__], "Show", Show)
  3000. return cls
  3001. class ShowBase(_Backend):
  3002. """
  3003. Simple base class to generate a ``show()`` function in backends.
  3004. Subclass must override ``mainloop()`` method.
  3005. """
  3006. def __call__(self, block=None):
  3007. return self.show(block=block)