| 1 |
# -*- coding: utf-8 -*- |
| 2 |
"""Pylab (matplotlib) support utilities.""" |
| 3 |
|
| 4 |
# Copyright (c) IPython Development Team. |
| 5 |
# Distributed under the terms of the Modified BSD License. |
| 6 |
|
| 7 |
from io import BytesIO |
| 8 |
from binascii import b2a_base64 |
| 9 |
from functools import partial |
| 10 |
import warnings |
| 11 |
|
| 12 |
from IPython.core.display import _pngxy |
| 13 |
from IPython.utils.decorators import flag_calls |
| 14 |
|
| 15 |
|
| 16 |
# Matplotlib backend resolution functionality moved from IPython to Matplotlib |
| 17 |
# in IPython 8.24 and Matplotlib 3.9.0. Need to keep `backends` and `backend2gui` |
| 18 |
# here for earlier Matplotlib and for external backend libraries such as |
| 19 |
# mplcairo that might rely upon it. |
| 20 |
_deprecated_backends = { |
| 21 |
"tk": "TkAgg", |
| 22 |
"gtk": "GTKAgg", |
| 23 |
"gtk3": "GTK3Agg", |
| 24 |
"gtk4": "GTK4Agg", |
| 25 |
"wx": "WXAgg", |
| 26 |
"qt4": "Qt4Agg", |
| 27 |
"qt5": "Qt5Agg", |
| 28 |
"qt6": "QtAgg", |
| 29 |
"qt": "QtAgg", |
| 30 |
"osx": "MacOSX", |
| 31 |
"nbagg": "nbAgg", |
| 32 |
"webagg": "WebAgg", |
| 33 |
"notebook": "nbAgg", |
| 34 |
"agg": "agg", |
| 35 |
"svg": "svg", |
| 36 |
"pdf": "pdf", |
| 37 |
"ps": "ps", |
| 38 |
"inline": "module://matplotlib_inline.backend_inline", |
| 39 |
"ipympl": "module://ipympl.backend_nbagg", |
| 40 |
"widget": "module://ipympl.backend_nbagg", |
| 41 |
} |
| 42 |
|
| 43 |
# We also need a reverse backends2guis mapping that will properly choose which |
| 44 |
# GUI support to activate based on the desired matplotlib backend. For the |
| 45 |
# most part it's just a reverse of the above dict, but we also need to add a |
| 46 |
# few others that map to the same GUI manually: |
| 47 |
_deprecated_backend2gui = dict( |
| 48 |
zip(_deprecated_backends.values(), _deprecated_backends.keys()) |
| 49 |
) |
| 50 |
# In the reverse mapping, there are a few extra valid matplotlib backends that |
| 51 |
# map to the same GUI support |
| 52 |
_deprecated_backend2gui["GTK"] = _deprecated_backend2gui["GTKCairo"] = "gtk" |
| 53 |
_deprecated_backend2gui["GTK3Cairo"] = "gtk3" |
| 54 |
_deprecated_backend2gui["GTK4Cairo"] = "gtk4" |
| 55 |
_deprecated_backend2gui["WX"] = "wx" |
| 56 |
_deprecated_backend2gui["CocoaAgg"] = "osx" |
| 57 |
# There needs to be a hysteresis here as the new QtAgg Matplotlib backend |
| 58 |
# supports either Qt5 or Qt6 and the IPython qt event loop support Qt4, Qt5, |
| 59 |
# and Qt6. |
| 60 |
_deprecated_backend2gui["QtAgg"] = "qt" |
| 61 |
_deprecated_backend2gui["Qt4Agg"] = "qt4" |
| 62 |
_deprecated_backend2gui["Qt5Agg"] = "qt5" |
| 63 |
|
| 64 |
# And some backends that don't need GUI integration |
| 65 |
del _deprecated_backend2gui["nbAgg"] |
| 66 |
del _deprecated_backend2gui["agg"] |
| 67 |
del _deprecated_backend2gui["svg"] |
| 68 |
del _deprecated_backend2gui["pdf"] |
| 69 |
del _deprecated_backend2gui["ps"] |
| 70 |
del _deprecated_backend2gui["module://matplotlib_inline.backend_inline"] |
| 71 |
del _deprecated_backend2gui["module://ipympl.backend_nbagg"] |
| 72 |
|
| 73 |
|
| 74 |
# Deprecated attributes backends and backend2gui mostly following PEP 562. |
| 75 |
def __getattr__(name): |
| 76 |
if name in ("backends", "backend2gui"): |
| 77 |
warnings.warn( |
| 78 |
f"{name} is deprecated since IPython 8.24, backends are managed " |
| 79 |
"in matplotlib and can be externally registered.", |
| 80 |
DeprecationWarning, |
| 81 |
) |
| 82 |
return globals()[f"_deprecated_{name}"] |
| 83 |
raise AttributeError(f"module {__name__!r} has no attribute {name!r}") |
| 84 |
|
| 85 |
|
| 86 |
#----------------------------------------------------------------------------- |
| 87 |
# Matplotlib utilities |
| 88 |
#----------------------------------------------------------------------------- |
| 89 |
|
| 90 |
|
| 91 |
def getfigs(*fig_nums): |
| 92 |
"""Get a list of matplotlib figures by figure numbers. |
| 93 |
|
| 94 |
If no arguments are given, all available figures are returned. If the |
| 95 |
argument list contains references to invalid figures, a warning is printed |
| 96 |
but the function continues pasting further figures. |
| 97 |
|
| 98 |
Parameters |
| 99 |
---------- |
| 100 |
figs : tuple |
| 101 |
A tuple of ints giving the figure numbers of the figures to return. |
| 102 |
""" |
| 103 |
from matplotlib._pylab_helpers import Gcf |
| 104 |
if not fig_nums: |
| 105 |
fig_managers = Gcf.get_all_fig_managers() |
| 106 |
return [fm.canvas.figure for fm in fig_managers] |
| 107 |
else: |
| 108 |
figs = [] |
| 109 |
for num in fig_nums: |
| 110 |
f = Gcf.figs.get(num) |
| 111 |
if f is None: |
| 112 |
print('Warning: figure %s not available.' % num) |
| 113 |
else: |
| 114 |
figs.append(f.canvas.figure) |
| 115 |
return figs |
| 116 |
|
| 117 |
|
| 118 |
def figsize(sizex, sizey): |
| 119 |
"""Set the default figure size to be [sizex, sizey]. |
| 120 |
|
| 121 |
This is just an easy to remember, convenience wrapper that sets:: |
| 122 |
|
| 123 |
matplotlib.rcParams['figure.figsize'] = [sizex, sizey] |
| 124 |
""" |
| 125 |
import matplotlib |
| 126 |
matplotlib.rcParams['figure.figsize'] = [sizex, sizey] |
| 127 |
|
| 128 |
|
| 129 |
def print_figure(fig, fmt="png", bbox_inches="tight", base64=False, **kwargs): |
| 130 |
"""Print a figure to an image, and return the resulting file data |
| 131 |
|
| 132 |
Returned data will be bytes unless ``fmt='svg'``, |
| 133 |
in which case it will be unicode. |
| 134 |
|
| 135 |
Any keyword args are passed to fig.canvas.print_figure, |
| 136 |
such as ``quality`` or ``bbox_inches``. |
| 137 |
|
| 138 |
If `base64` is True, return base64-encoded str instead of raw bytes |
| 139 |
for binary-encoded image formats |
| 140 |
|
| 141 |
.. versionadded:: 7.29 |
| 142 |
base64 argument |
| 143 |
""" |
| 144 |
# When there's an empty figure, we shouldn't return anything, otherwise we |
| 145 |
# get big blank areas in the qt console. |
| 146 |
if not fig.axes and not fig.lines: |
| 147 |
return |
| 148 |
|
| 149 |
dpi = fig.dpi |
| 150 |
if fmt == 'retina': |
| 151 |
dpi = dpi * 2 |
| 152 |
fmt = 'png' |
| 153 |
|
| 154 |
# build keyword args |
| 155 |
kw = { |
| 156 |
"format":fmt, |
| 157 |
"facecolor":fig.get_facecolor(), |
| 158 |
"edgecolor":fig.get_edgecolor(), |
| 159 |
"dpi":dpi, |
| 160 |
"bbox_inches":bbox_inches, |
| 161 |
} |
| 162 |
# **kwargs get higher priority |
| 163 |
kw.update(kwargs) |
| 164 |
|
| 165 |
bytes_io = BytesIO() |
| 166 |
if fig.canvas is None: |
| 167 |
from matplotlib.backend_bases import FigureCanvasBase |
| 168 |
FigureCanvasBase(fig) |
| 169 |
|
| 170 |
fig.canvas.print_figure(bytes_io, **kw) |
| 171 |
data = bytes_io.getvalue() |
| 172 |
if fmt == 'svg': |
| 173 |
data = data.decode('utf-8') |
| 174 |
elif base64: |
| 175 |
data = b2a_base64(data, newline=False).decode("ascii") |
| 176 |
return data |
| 177 |
|
| 178 |
def retina_figure(fig, base64=False, **kwargs): |
| 179 |
"""format a figure as a pixel-doubled (retina) PNG |
| 180 |
|
| 181 |
If `base64` is True, return base64-encoded str instead of raw bytes |
| 182 |
for binary-encoded image formats |
| 183 |
|
| 184 |
.. versionadded:: 7.29 |
| 185 |
base64 argument |
| 186 |
""" |
| 187 |
pngdata = print_figure(fig, fmt="retina", base64=False, **kwargs) |
| 188 |
# Make sure that retina_figure acts just like print_figure and returns |
| 189 |
# None when the figure is empty. |
| 190 |
if pngdata is None: |
| 191 |
return |
| 192 |
w, h = _pngxy(pngdata) |
| 193 |
metadata = {"width": w//2, "height":h//2} |
| 194 |
if base64: |
| 195 |
pngdata = b2a_base64(pngdata, newline=False).decode("ascii") |
| 196 |
return pngdata, metadata |
| 197 |
|
| 198 |
|
| 199 |
# We need a little factory function here to create the closure where |
| 200 |
# safe_execfile can live. |
| 201 |
def mpl_runner(safe_execfile): |
| 202 |
"""Factory to return a matplotlib-enabled runner for %run. |
| 203 |
|
| 204 |
Parameters |
| 205 |
---------- |
| 206 |
safe_execfile : function |
| 207 |
This must be a function with the same interface as the |
| 208 |
:meth:`safe_execfile` method of IPython. |
| 209 |
|
| 210 |
Returns |
| 211 |
------- |
| 212 |
A function suitable for use as the ``runner`` argument of the %run magic |
| 213 |
function. |
| 214 |
""" |
| 215 |
|
| 216 |
def mpl_execfile(fname,*where,**kw): |
| 217 |
"""matplotlib-aware wrapper around safe_execfile. |
| 218 |
|
| 219 |
Its interface is identical to that of the :func:`execfile` builtin. |
| 220 |
|
| 221 |
This is ultimately a call to execfile(), but wrapped in safeties to |
| 222 |
properly handle interactive rendering.""" |
| 223 |
|
| 224 |
import matplotlib |
| 225 |
import matplotlib.pyplot as plt |
| 226 |
|
| 227 |
# print('*** Matplotlib runner ***') # dbg |
| 228 |
# turn off rendering until end of script |
| 229 |
with matplotlib.rc_context({"interactive": False}): |
| 230 |
safe_execfile(fname, *where, **kw) |
| 231 |
|
| 232 |
if matplotlib.is_interactive(): |
| 233 |
plt.show() |
| 234 |
|
| 235 |
# make rendering call now, if the user tried to do it |
| 236 |
if plt.draw_if_interactive.called: |
| 237 |
plt.draw() |
| 238 |
plt.draw_if_interactive.called = False |
| 239 |
|
| 240 |
# re-draw everything that is stale |
| 241 |
try: |
| 242 |
da = plt.draw_all |
| 243 |
except AttributeError: |
| 244 |
pass |
| 245 |
else: |
| 246 |
da() |
| 247 |
|
| 248 |
return mpl_execfile |
| 249 |
|
| 250 |
|
| 251 |
def _reshow_nbagg_figure(fig): |
| 252 |
"""reshow an nbagg figure""" |
| 253 |
try: |
| 254 |
reshow = fig.canvas.manager.reshow |
| 255 |
except AttributeError as e: |
| 256 |
raise NotImplementedError() from e |
| 257 |
else: |
| 258 |
reshow() |
| 259 |
|
| 260 |
|
| 261 |
def select_figure_formats(shell, formats, **kwargs): |
| 262 |
"""Select figure formats for the inline backend. |
| 263 |
|
| 264 |
Parameters |
| 265 |
---------- |
| 266 |
shell : InteractiveShell |
| 267 |
The main IPython instance. |
| 268 |
formats : str or set |
| 269 |
One or a set of figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'. |
| 270 |
**kwargs : any |
| 271 |
Extra keyword arguments to be passed to fig.canvas.print_figure. |
| 272 |
""" |
| 273 |
import matplotlib |
| 274 |
from matplotlib.figure import Figure |
| 275 |
|
| 276 |
svg_formatter = shell.display_formatter.formatters['image/svg+xml'] |
| 277 |
png_formatter = shell.display_formatter.formatters['image/png'] |
| 278 |
jpg_formatter = shell.display_formatter.formatters['image/jpeg'] |
| 279 |
pdf_formatter = shell.display_formatter.formatters['application/pdf'] |
| 280 |
|
| 281 |
if isinstance(formats, str): |
| 282 |
formats = {formats} |
| 283 |
# cast in case of list / tuple |
| 284 |
formats = set(formats) |
| 285 |
|
| 286 |
[ f.pop(Figure, None) for f in shell.display_formatter.formatters.values() ] |
| 287 |
mplbackend = matplotlib.get_backend().lower() |
| 288 |
if mplbackend in ("nbagg", "ipympl", "widget", "module://ipympl.backend_nbagg"): |
| 289 |
formatter = shell.display_formatter.ipython_display_formatter |
| 290 |
formatter.for_type(Figure, _reshow_nbagg_figure) |
| 291 |
|
| 292 |
supported = {'png', 'png2x', 'retina', 'jpg', 'jpeg', 'svg', 'pdf'} |
| 293 |
bad = formats.difference(supported) |
| 294 |
if bad: |
| 295 |
bs = "%s" % ','.join([repr(f) for f in bad]) |
| 296 |
gs = "%s" % ','.join([repr(f) for f in supported]) |
| 297 |
raise ValueError("supported formats are: %s not %s" % (gs, bs)) |
| 298 |
|
| 299 |
if "png" in formats: |
| 300 |
png_formatter.for_type( |
| 301 |
Figure, partial(print_figure, fmt="png", base64=True, **kwargs) |
| 302 |
) |
| 303 |
if "retina" in formats or "png2x" in formats: |
| 304 |
png_formatter.for_type(Figure, partial(retina_figure, base64=True, **kwargs)) |
| 305 |
if "jpg" in formats or "jpeg" in formats: |
| 306 |
jpg_formatter.for_type( |
| 307 |
Figure, partial(print_figure, fmt="jpg", base64=True, **kwargs) |
| 308 |
) |
| 309 |
if "svg" in formats: |
| 310 |
svg_formatter.for_type(Figure, partial(print_figure, fmt="svg", **kwargs)) |
| 311 |
if "pdf" in formats: |
| 312 |
pdf_formatter.for_type( |
| 313 |
Figure, partial(print_figure, fmt="pdf", base64=True, **kwargs) |
| 314 |
) |
| 315 |
|
| 316 |
#----------------------------------------------------------------------------- |
| 317 |
# Code for initializing matplotlib and importing pylab |
| 318 |
#----------------------------------------------------------------------------- |
| 319 |
|
| 320 |
|
| 321 |
def find_gui_and_backend(gui=None, gui_select=None): |
| 322 |
"""Given a gui string return the gui and mpl backend. |
| 323 |
|
| 324 |
Parameters |
| 325 |
---------- |
| 326 |
gui : str |
| 327 |
Can be one of ('tk','gtk','wx','qt','qt4','inline','agg'). |
| 328 |
gui_select : str |
| 329 |
Can be one of ('tk','gtk','wx','qt','qt4','inline'). |
| 330 |
This is any gui already selected by the shell. |
| 331 |
|
| 332 |
Returns |
| 333 |
------- |
| 334 |
A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg', |
| 335 |
'WXAgg','Qt4Agg','module://matplotlib_inline.backend_inline','agg'). |
| 336 |
""" |
| 337 |
|
| 338 |
import matplotlib |
| 339 |
|
| 340 |
if _matplotlib_manages_backends(): |
| 341 |
backend_registry = matplotlib.backends.registry.backend_registry |
| 342 |
|
| 343 |
# gui argument may be a gui event loop or may be a backend name. |
| 344 |
if gui in ("auto", None): |
| 345 |
backend = matplotlib.rcParamsOrig["backend"] |
| 346 |
backend, gui = backend_registry.resolve_backend(backend) |
| 347 |
else: |
| 348 |
gui = _convert_gui_to_matplotlib(gui) |
| 349 |
backend, gui = backend_registry.resolve_gui_or_backend(gui) |
| 350 |
|
| 351 |
gui = _convert_gui_from_matplotlib(gui) |
| 352 |
return gui, backend |
| 353 |
|
| 354 |
# Fallback to previous behaviour (Matplotlib < 3.9) |
| 355 |
mpl_version_info = getattr(matplotlib, "__version_info__", (0, 0)) |
| 356 |
has_unified_qt_backend = mpl_version_info >= (3, 5) |
| 357 |
|
| 358 |
|
| 359 |
backends_ = dict(_deprecated_backends) |
| 360 |
if not has_unified_qt_backend: |
| 361 |
backends_["qt"] = "qt5agg" |
| 362 |
|
| 363 |
if gui and gui != 'auto': |
| 364 |
# select backend based on requested gui |
| 365 |
backend = backends_[gui] |
| 366 |
if gui == 'agg': |
| 367 |
gui = None |
| 368 |
else: |
| 369 |
# We need to read the backend from the original data structure, *not* |
| 370 |
# from mpl.rcParams, since a prior invocation of %matplotlib may have |
| 371 |
# overwritten that. |
| 372 |
# WARNING: this assumes matplotlib 1.1 or newer!! |
| 373 |
backend = matplotlib.rcParamsOrig['backend'] |
| 374 |
|
| 375 |
# In this case, we need to find what the appropriate gui selection call |
| 376 |
# should be for IPython, so we can activate inputhook accordingly |
| 377 |
gui = _deprecated_backend2gui.get(backend, None) |
| 378 |
|
| 379 |
# If we have already had a gui active, we need it and inline are the |
| 380 |
# ones allowed. |
| 381 |
if gui_select and gui != gui_select: |
| 382 |
gui = gui_select |
| 383 |
backend = backends_[gui] |
| 384 |
|
| 385 |
# Matplotlib before _matplotlib_manages_backends() can return "inline" for |
| 386 |
# no gui event loop rather than the None that IPython >= 8.24.0 expects. |
| 387 |
if gui == "inline": |
| 388 |
gui = None |
| 389 |
|
| 390 |
return gui, backend |
| 391 |
|
| 392 |
|
| 393 |
def activate_matplotlib(backend): |
| 394 |
"""Activate the given backend and set interactive to True.""" |
| 395 |
|
| 396 |
import matplotlib |
| 397 |
matplotlib.interactive(True) |
| 398 |
|
| 399 |
# Matplotlib had a bug where even switch_backend could not force |
| 400 |
# the rcParam to update. This needs to be set *before* the module |
| 401 |
# magic of switch_backend(). |
| 402 |
matplotlib.rcParams['backend'] = backend |
| 403 |
|
| 404 |
# Due to circular imports, pyplot may be only partially initialised |
| 405 |
# when this function runs. |
| 406 |
# So avoid needing matplotlib attribute-lookup to access pyplot. |
| 407 |
from matplotlib import pyplot as plt |
| 408 |
|
| 409 |
plt.switch_backend(backend) |
| 410 |
|
| 411 |
plt.show._needmain = False |
| 412 |
# We need to detect at runtime whether show() is called by the user. |
| 413 |
# For this, we wrap it into a decorator which adds a 'called' flag. |
| 414 |
plt.draw_if_interactive = flag_calls(plt.draw_if_interactive) |
| 415 |
|
| 416 |
|
| 417 |
def import_pylab(user_ns, import_all=True): |
| 418 |
"""Populate the namespace with pylab-related values. |
| 419 |
|
| 420 |
Imports matplotlib, pylab, numpy, and everything from pylab and numpy. |
| 421 |
|
| 422 |
Also imports a few names from IPython (figsize, display, getfigs) |
| 423 |
|
| 424 |
""" |
| 425 |
|
| 426 |
# Import numpy as np/pyplot as plt are conventions we're trying to |
| 427 |
# somewhat standardize on. Making them available to users by default |
| 428 |
# will greatly help this. |
| 429 |
s = ("import numpy\n" |
| 430 |
"import matplotlib\n" |
| 431 |
"from matplotlib import pylab, mlab, pyplot\n" |
| 432 |
"np = numpy\n" |
| 433 |
"plt = pyplot\n" |
| 434 |
) |
| 435 |
exec(s, user_ns) |
| 436 |
|
| 437 |
if import_all: |
| 438 |
s = ("from matplotlib.pylab import *\n" |
| 439 |
"from numpy import *\n") |
| 440 |
exec(s, user_ns) |
| 441 |
|
| 442 |
# IPython symbols to add |
| 443 |
user_ns['figsize'] = figsize |
| 444 |
from IPython.display import display |
| 445 |
# Add display and getfigs to the user's namespace |
| 446 |
user_ns['display'] = display |
| 447 |
user_ns['getfigs'] = getfigs |
| 448 |
|
| 449 |
|
| 450 |
# Determine if Matplotlib manages backends only if needed, and cache result. |
| 451 |
# Do not read this directly, instead use _matplotlib_manages_backends(). |
| 452 |
_matplotlib_manages_backends_value: bool | None = None |
| 453 |
|
| 454 |
|
| 455 |
def _matplotlib_manages_backends() -> bool: |
| 456 |
"""Return True if Matplotlib manages backends, False otherwise. |
| 457 |
|
| 458 |
If it returns True, the caller can be sure that |
| 459 |
matplotlib.backends.registry.backend_registry is available along with |
| 460 |
member functions resolve_gui_or_backend, resolve_backend, list_all, and |
| 461 |
list_gui_frameworks. |
| 462 |
|
| 463 |
This function can be removed as it will always return True when Python |
| 464 |
3.12, the latest version supported by Matplotlib < 3.9, reaches |
| 465 |
end-of-life in late 2028. |
| 466 |
""" |
| 467 |
global _matplotlib_manages_backends_value |
| 468 |
if _matplotlib_manages_backends_value is None: |
| 469 |
try: |
| 470 |
from matplotlib.backends.registry import backend_registry |
| 471 |
|
| 472 |
_matplotlib_manages_backends_value = hasattr( |
| 473 |
backend_registry, "resolve_gui_or_backend" |
| 474 |
) |
| 475 |
except ImportError: |
| 476 |
_matplotlib_manages_backends_value = False |
| 477 |
|
| 478 |
return _matplotlib_manages_backends_value |
| 479 |
|
| 480 |
|
| 481 |
def _list_matplotlib_backends_and_gui_loops() -> list[str]: |
| 482 |
"""Return list of all Matplotlib backends and GUI event loops. |
| 483 |
|
| 484 |
This is the list returned by |
| 485 |
%matplotlib --list |
| 486 |
""" |
| 487 |
if _matplotlib_manages_backends(): |
| 488 |
from matplotlib.backends.registry import backend_registry |
| 489 |
|
| 490 |
ret = backend_registry.list_all() + [ |
| 491 |
_convert_gui_from_matplotlib(gui) |
| 492 |
for gui in backend_registry.list_gui_frameworks() |
| 493 |
] |
| 494 |
else: |
| 495 |
from IPython.core import pylabtools |
| 496 |
|
| 497 |
ret = list(pylabtools.backends.keys()) |
| 498 |
|
| 499 |
return sorted(["auto"] + ret) |
| 500 |
|
| 501 |
|
| 502 |
# Matplotlib and IPython do not always use the same gui framework name. |
| 503 |
# Always use the appropriate one of these conversion functions when passing a |
| 504 |
# gui framework name to/from Matplotlib. |
| 505 |
def _convert_gui_to_matplotlib(gui: str | None) -> str | None: |
| 506 |
if gui and gui.lower() == "osx": |
| 507 |
return "macosx" |
| 508 |
return gui |
| 509 |
|
| 510 |
|
| 511 |
def _convert_gui_from_matplotlib(gui: str | None) -> str | None: |
| 512 |
if gui and gui.lower() == "macosx": |
| 513 |
return "osx" |
| 514 |
return gui |