"""\
Copyright (c) 2023, Flagstaff Solutions, LLC
All rights reserved.
"""
import inspect
import io
import matplotlib
import matplotlib.pyplot as plt
from gofigr.backends import GoFigrBackend, get_all_function_arguments
[docs]
class SuppressPltWarnings:
"""Temporarily suppresses matplotlib warnings."""
def __init__(self):
self.plt_log = None
self.log_level = None
def __enter__(self):
# Save initial log level
self.plt_log = getattr(plt, "_log")
self.log_level = getattr(self.plt_log, "level") if self.plt_log is not None else None
plt.set_loglevel("error")
def __exit__(self, exc_type, exc_val, exc_tb):
# Restore log level
if self.plt_log is not None and self.log_level is not None:
self.plt_log.setLevel(self.log_level)
[docs]
class MatplotlibBackend(GoFigrBackend):
"""\
MatplotLib backend for GoFigr.
"""
[docs]
def get_backend_name(self):
return "matplotlib"
[docs]
def is_compatible(self, fig):
return isinstance(fig, matplotlib.figure.Figure)
[docs]
def is_interactive(self, fig):
return False
[docs]
@staticmethod
def title_to_string(title):
"""Extracts the title as a string from a title-like object (e.g. Text)"""
if title is None:
return None
elif isinstance(title, matplotlib.text.Text):
return title.get_text()
elif isinstance(title, str):
return title
else:
return None
[docs]
def get_title(self, fig):
suptitle = MatplotlibBackend.title_to_string(getattr(fig, "_suptitle", ""))
# get_title() only reads the requested slot, and a figure titled with
# loc="left"/"right" has an empty center slot — check all three so
# such figures don't publish as 'Anonymous Figure'.
title = None
if len(fig.axes) > 0:
for loc in ("center", "left", "right"):
title = MatplotlibBackend.title_to_string(fig.axes[0].get_title(loc=loc))
if title is not None and title.strip() != "":
break
if suptitle is not None and suptitle.strip() != "":
return suptitle
elif title is not None and title.strip() != "":
return title
else:
return None
[docs]
def close(self, fig):
plt.close(fig)