backend_bases.py 115 KB

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