Ensure matplotlib backend gets reset with plt_settings (#15759)

Co-authored-by: UltralyticsAssistant <web@ultralytics.com>
Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com>
This commit is contained in:
Robert Schroll 2024-08-22 20:48:41 -07:00 committed by GitHub
parent 8bb776fbc3
commit a89b316f27
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -219,16 +219,19 @@ def plt_settings(rcparams=None, backend="Agg"):
def wrapper(*args, **kwargs): def wrapper(*args, **kwargs):
"""Sets rc parameters and backend, calls the original function, and restores the settings.""" """Sets rc parameters and backend, calls the original function, and restores the settings."""
original_backend = plt.get_backend() original_backend = plt.get_backend()
if backend.lower() != original_backend.lower(): switch = backend.lower() != original_backend.lower()
if switch:
plt.close("all") # auto-close()ing of figures upon backend switching is deprecated since 3.8 plt.close("all") # auto-close()ing of figures upon backend switching is deprecated since 3.8
plt.switch_backend(backend) plt.switch_backend(backend)
with plt.rc_context(rcparams): # Plot with backend and always revert to original backend
result = func(*args, **kwargs) try:
with plt.rc_context(rcparams):
if backend != original_backend: result = func(*args, **kwargs)
plt.close("all") finally:
plt.switch_backend(original_backend) if switch:
plt.close("all")
plt.switch_backend(original_backend)
return result return result
return wrapper return wrapper