-
Notifications
You must be signed in to change notification settings - Fork 45
Implementation of matplotlib
backend for criterion_plot()
#599
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
e187294
0159fe6
e167b49
f15d982
f1fcdaa
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,173 @@ | ||
from typing import Any, Literal, Protocol, runtime_checkable | ||
|
||
import plotly.graph_objects as go | ||
|
||
from optimagic.config import IS_MATPLOTLIB_INSTALLED | ||
from optimagic.exceptions import InvalidPlottingBackendError, NotInstalledError | ||
from optimagic.visualization.plotting_utilities import LineData | ||
|
||
if IS_MATPLOTLIB_INSTALLED: | ||
import matplotlib as mpl | ||
import matplotlib.pyplot as plt | ||
|
||
# Handle the case where matplotlib is used in notebooks (inline backend) | ||
# to ensure that interactive mode is disabled to avoid double plotting. | ||
# (See: https://github.com/matplotlib/matplotlib/issues/26221) | ||
if mpl.get_backend() == "module://matplotlib_inline.backend_inline": | ||
plt.install_repl_displayhook() | ||
plt.ioff() | ||
Comment on lines
+13
to
+18
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As discussed, we will check how other libraries solve this problem before continuing with this approach. |
||
|
||
|
||
@runtime_checkable | ||
class LinePlotFunction(Protocol): | ||
def __call__( | ||
self, | ||
lines: list[LineData], | ||
*, | ||
title: str | None, | ||
xlabel: str | None, | ||
ylabel: str | None, | ||
template: str | None, | ||
height: int | None, | ||
width: int | None, | ||
legend_properties: dict[str, Any] | None, | ||
) -> Any: ... | ||
|
||
|
||
def _line_plot_plotly( | ||
lines: list[LineData], | ||
*, | ||
title: str | None, | ||
xlabel: str | None, | ||
ylabel: str | None, | ||
template: str | None, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Don't w need to set the default template if |
||
height: int | None, | ||
width: int | None, | ||
legend_properties: dict[str, Any] | None, | ||
) -> go.Figure: | ||
fig = go.Figure() | ||
|
||
for line in lines: | ||
trace = go.Scatter( | ||
x=line.x, | ||
y=line.y, | ||
name=line.name, | ||
line_color=line.color, | ||
mode="lines", | ||
) | ||
fig.add_trace(trace) | ||
|
||
fig.update_layout( | ||
title=title, | ||
xaxis_title=xlabel, | ||
yaxis_title=ylabel, | ||
template=template, | ||
height=height, | ||
width=width, | ||
) | ||
|
||
if legend_properties: | ||
fig.update_layout(legend=legend_properties) | ||
|
||
return fig | ||
|
||
|
||
def _line_plot_matplotlib( | ||
lines: list[LineData], | ||
*, | ||
title: str | None, | ||
xlabel: str | None, | ||
ylabel: str | None, | ||
template: str | None, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Don't we need to set a default if |
||
height: int | None, | ||
width: int | None, | ||
legend_properties: dict[str, Any] | None, | ||
) -> "plt.Figure": | ||
if template is not None: | ||
plt.style.use(template) | ||
fig, ax = plt.subplots(figsize=(width, height) if width and height else None) | ||
|
||
for line in lines: | ||
ax.plot( | ||
line.x, | ||
line.y, | ||
label=line.name if line.show_in_legend else None, | ||
color=line.color, | ||
) | ||
|
||
ax.set(title=title, xlabel=xlabel, ylabel=ylabel) | ||
if legend_properties: | ||
ax.legend(**legend_properties) | ||
|
||
return fig | ||
|
||
|
||
BACKEND_AVAILABILITY_AND_LINE_PLOT_FUNCTION: dict[ | ||
str, tuple[bool, LinePlotFunction] | ||
] = { | ||
"plotly": (True, _line_plot_plotly), | ||
"matplotlib": (IS_MATPLOTLIB_INSTALLED, _line_plot_matplotlib), | ||
} | ||
|
||
|
||
def line_plot( | ||
lines: list[LineData], | ||
backend: Literal["plotly", "matplotlib"] = "plotly", | ||
*, | ||
title: str | None = None, | ||
xlabel: str | None = None, | ||
ylabel: str | None = None, | ||
template: str | None = None, | ||
height: int | None = None, | ||
width: int | None = None, | ||
legend_properties: dict[str, Any] | None = None, | ||
) -> Any: | ||
"""Create a line plot corresponding to the specified backend. | ||
|
||
Args: | ||
lines: List of objects each containing data for a line in the plot. | ||
backend: The backend to use for plotting. | ||
title: Title of the plot. | ||
xlabel: Label for the x-axis. | ||
ylabel: Label for the y-axis. | ||
template: Backend-specific template for styling the plot. | ||
height: Height of the plot (in pixels). | ||
width: Width of the plot (in pixels). | ||
legend_properties: Backend-specific properties for the legend. | ||
|
||
Returns: | ||
A figure object corresponding to the specified backend. | ||
|
||
""" | ||
if backend not in BACKEND_AVAILABILITY_AND_LINE_PLOT_FUNCTION: | ||
msg = ( | ||
f"Invalid plotting backend '{backend}'. " | ||
f"Available backends: " | ||
f"{', '.join(BACKEND_AVAILABILITY_AND_LINE_PLOT_FUNCTION.keys())}" | ||
) | ||
raise InvalidPlottingBackendError(msg) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can you create a testing file for this module. There you should test:
|
||
|
||
_is_backend_available, _line_plot_backend_function = ( | ||
BACKEND_AVAILABILITY_AND_LINE_PLOT_FUNCTION[backend] | ||
) | ||
|
||
if not _is_backend_available: | ||
msg = ( | ||
f"The {backend} backend is not installed. " | ||
f"Install the package using either 'pip install {backend}' or " | ||
f"'conda install -c conda-forge {backend}'" | ||
) | ||
raise NotInstalledError(msg) | ||
|
||
fig = _line_plot_backend_function( | ||
lines, | ||
title=title, | ||
xlabel=xlabel, | ||
ylabel=ylabel, | ||
template=template, | ||
height=height, | ||
width=width, | ||
legend_properties=legend_properties, | ||
) | ||
|
||
return fig |
Uh oh!
There was an error while loading. Please reload this page.