backend_bases.py 124 KB

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