From e4bf042a0ce65dacd108782aa1ba577b8fb9277d Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Thu, 3 Dec 2026 03:08:07 +0000 Subject: [PATCH 01/23] Port the matplotlylib tests from plotly.py Copy tests/test_optional/test_matplotlylib (8 test modules and their expected data) from plotly.py, together with the helpers they use, tests/utils.py and tests/test_optional/optional_utils.py. Changes from the plotly.py versions: - Import matplotlylib and matplotlib directly. plotly.py looked them up through plotly.optional_imports because they were optional there; here they are always installed. - Call matplotlylib.mpl_to_plotly in test_date_times instead of plotly.tools.mpl_to_plotly, which runs plotly's own copy of matplotlylib. - Remove the @pytest.mark.skip marks, which plotly.py added in 2022, and the pytest imports left unused by that. Add pandas to the dev extras, since test_date_times imports it. 12 of the 16 ported tests fail and are fixed in later commits. --- pyproject.toml | 2 +- tests/test_optional/__init__.py | 7 + tests/test_optional/optional_utils.py | 118 +++++++++ .../test_matplotlylib/__init__.py | 5 + .../test_matplotlylib/data/__init__.py | 1 + .../test_matplotlylib/data/annotations.py | 106 ++++++++ .../test_matplotlylib/data/axis_scales.py | 56 ++++ .../test_matplotlylib/data/bars.py | 174 ++++++++++++ .../test_matplotlylib/data/data.py | 6 + .../test_matplotlylib/data/lines.py | 149 +++++++++++ .../test_matplotlylib/data/scatter.py | 130 +++++++++ .../test_matplotlylib/data/subplots.py | 249 ++++++++++++++++++ .../test_matplotlylib/test_annotations.py | 29 ++ .../test_matplotlylib/test_axis_scales.py | 30 +++ .../test_matplotlylib/test_bars.py | 80 ++++++ .../test_matplotlylib/test_data.py | 78 ++++++ .../test_matplotlylib/test_date_times.py | 67 +++++ .../test_matplotlylib/test_lines.py | 53 ++++ .../test_matplotlylib/test_scatter.py | 48 ++++ .../test_matplotlylib/test_subplots.py | 33 +++ tests/utils.py | 97 +++++++ 21 files changed, 1517 insertions(+), 1 deletion(-) create mode 100644 tests/test_optional/__init__.py create mode 100644 tests/test_optional/optional_utils.py create mode 100644 tests/test_optional/test_matplotlylib/__init__.py create mode 100644 tests/test_optional/test_matplotlylib/data/__init__.py create mode 100644 tests/test_optional/test_matplotlylib/data/annotations.py create mode 100644 tests/test_optional/test_matplotlylib/data/axis_scales.py create mode 100644 tests/test_optional/test_matplotlylib/data/bars.py create mode 100644 tests/test_optional/test_matplotlylib/data/data.py create mode 100644 tests/test_optional/test_matplotlylib/data/lines.py create mode 100644 tests/test_optional/test_matplotlylib/data/scatter.py create mode 100644 tests/test_optional/test_matplotlylib/data/subplots.py create mode 100644 tests/test_optional/test_matplotlylib/test_annotations.py create mode 100644 tests/test_optional/test_matplotlylib/test_axis_scales.py create mode 100644 tests/test_optional/test_matplotlylib/test_bars.py create mode 100644 tests/test_optional/test_matplotlylib/test_data.py create mode 100644 tests/test_optional/test_matplotlylib/test_date_times.py create mode 100644 tests/test_optional/test_matplotlylib/test_lines.py create mode 100644 tests/test_optional/test_matplotlylib/test_scatter.py create mode 100644 tests/test_optional/test_matplotlylib/test_subplots.py create mode 100644 tests/utils.py diff --git a/pyproject.toml b/pyproject.toml index cbc0163..ece95e0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -30,7 +30,7 @@ dependencies = [ ] [project.optional-dependencies] -dev = ["pytest", "packaging", "ruff==0.11.12"] +dev = ["pytest", "packaging", "pandas", "ruff==0.11.12"] [project.urls] Homepage = "https://github.com/plotly/matplotlylib" diff --git a/tests/test_optional/__init__.py b/tests/test_optional/__init__.py new file mode 100644 index 0000000..c127f04 --- /dev/null +++ b/tests/test_optional/__init__.py @@ -0,0 +1,7 @@ +try: + # Set matplotlib backend once here + import matplotlib + + matplotlib.use("Agg") +except Exception: + pass diff --git a/tests/test_optional/optional_utils.py b/tests/test_optional/optional_utils.py new file mode 100644 index 0000000..a67f3d3 --- /dev/null +++ b/tests/test_optional/optional_utils.py @@ -0,0 +1,118 @@ +import numpy as np + +from ..utils import is_num_list +from plotly.utils import get_by_path, node_generator + +import copy + +import matplotlib + +# Force matplotlib to not use any Xwindows backend. +matplotlib.use("Agg") +from matplotlylib import Exporter, PlotlyRenderer + + +def run_fig(fig): + renderer = PlotlyRenderer() + exporter = Exporter(renderer) + print(exporter) + exporter.run(fig) + return renderer + + +class NumpyTestUtilsMixin(object): + """Provides some helper functions to make testing easier.""" + + def _format_path(self, path): + str_path = [repr(p) for p in path] + return "[" + "][".join(sp for sp in str_path) + "]" + + def assert_fig_equal(self, d1, d2, msg=None, ignore=["uid"]): + """ + Helper function for assert_dict_equal + + By default removes uid from d1 and/or d2 if present + then calls assert_dict_equal. + + :param (list|tuple) ignore: sequence of key names as + strings that are removed from both d1 and d2 if + they exist + """ + # deep copy d1 and d2 + if "to_plotly_json" in dir(d1): + d1_copy = copy.deepcopy(d1.to_plotly_json()) + else: + d1_copy = copy.deepcopy(d1) + + if "to_plotly_json" in dir(d2): + d2_copy = copy.deepcopy(d2.to_plotly_json()) + else: + d2_copy = copy.deepcopy(d2) + + for key in ignore: + if key in d1_copy.keys(): + del d1_copy[key] + if key in d2_copy.keys(): + del d2_copy[key] + + self.assert_dict_equal(d1_copy, d2_copy, msg=None) + + def assert_dict_equal(self, d1, d2, msg=None): + """ + Uses `np.allclose()` on number arrays. + + :raises: (AssertionError) Using TestCase's self.failureException + + """ + self.assertIsInstance(d1, dict, "First argument is not a dictionary") + self.assertIsInstance(d2, dict, "Second argument is not a dictionary") + + for node, path in node_generator(d1): + # first check that this sub-dict is contained in both dicts + try: + comp_node = get_by_path(d2, path) + except (KeyError, IndexError): + standard_msg = "Path {} exists in dict 1, but not dict 2.".format(path) + self.fail(self._formatMessage(msg, standard_msg)) + self.assertIsInstance( + comp_node, dict, "Value at path {} is not a dict.".format(path) + ) + + # check that each key in the first is contained in the second + for key, val in node.items(): + if isinstance(val, dict): + continue # this gets tested as its own node + + # check that the values at this key are equal + val_path = path + (key,) + try: + comp_val = comp_node[key] + except KeyError: + standard_msg = "Path {} exists in dict 1, but not dict 2.".format( + self._format_path(val_path) + ) + self.fail(self._formatMessage(msg, standard_msg)) + + if isinstance(val, np.ndarray) or isinstance(comp_val, np.ndarray): + if np.array_equal(val, comp_val): + continue + elif val == comp_val: + continue + + if is_num_list(val) and is_num_list(comp_val): + if np.allclose(val, comp_val): + continue + + standard_msg = "Value comparison failed at path {}.\n{} != {}".format( + self._format_path(val_path), val, comp_val + ) + self.fail(self._formatMessage(msg, standard_msg)) + + # finally, check that keys in the second are in the first + for key in comp_node: + val_path = path + (key,) + if key not in node: + standard_msg = "Path {} exists in dict 2, but not dict 1.".format( + self._format_path(val_path) + ) + self.fail(self._formatMessage(msg, standard_msg)) diff --git a/tests/test_optional/test_matplotlylib/__init__.py b/tests/test_optional/test_matplotlylib/__init__.py new file mode 100644 index 0000000..e1565c8 --- /dev/null +++ b/tests/test_optional/test_matplotlylib/__init__.py @@ -0,0 +1,5 @@ +import warnings + + +def setup_package(): + warnings.filterwarnings("ignore") diff --git a/tests/test_optional/test_matplotlylib/data/__init__.py b/tests/test_optional/test_matplotlylib/data/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/tests/test_optional/test_matplotlylib/data/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/test_optional/test_matplotlylib/data/annotations.py b/tests/test_optional/test_matplotlylib/data/annotations.py new file mode 100644 index 0000000..7ef3f2c --- /dev/null +++ b/tests/test_optional/test_matplotlylib/data/annotations.py @@ -0,0 +1,106 @@ +import plotly.graph_objs as go + +ANNOTATIONS = go.Figure( + data=[ + go.Scatter( + x=[0.0, 1.0, 2.0], + y=[1.0, 2.0, 3.0], + name="_line0", + mode="lines", + line=go.scatter.Line(dash="solid", color="rgba (0, 0, 255, 1)", width=1.5), + xaxis="x1", + yaxis="y1", + ), + go.Scatter( + x=[0.0, 1.0, 2.0], + y=[3.0, 2.0, 1.0], + name="_line1", + mode="lines", + line=go.scatter.Line(dash="solid", color="rgba (0, 0, 255, 1)", width=1.5), + xaxis="x1", + yaxis="y1", + ), + ], + layout=go.Layout( + width=640, + height=480, + autosize=False, + margin=go.layout.Margin(l=80, r=63, b=47, t=47, pad=0), + hovermode="closest", + showlegend=False, + annotations=[ + go.layout.Annotation( + x=0.000997987927565, + y=0.9973865229110511, + text="top-left", + xref="paper", + yref="paper", + showarrow=False, + align="left", + font=dict(size=10.0, color="#000000"), + opacity=1, + xanchor="left", + yanchor="top", + ), + go.layout.Annotation( + x=0.000997987927565, + y=0.0031525606469002573, + text="bottom-left", + xref="paper", + yref="paper", + align="left", + showarrow=False, + font=dict(size=10.0, color="#000000"), + opacity=1, + xanchor="left", + yanchor="bottom", + ), + go.layout.Annotation( + x=0.996989939638, + y=0.9973865229110511, + text="top-right", + xref="paper", + yref="paper", + align="right", + showarrow=False, + font=dict(size=10.0, color="#000000"), + opacity=1, + xanchor="right", + yanchor="top", + ), + go.layout.Annotation( + x=0.996989939638, + y=0.0031525606469002573, + text="bottom-right", + xref="paper", + yref="paper", + align="right", + showarrow=False, + font=dict(size=10.0, color="#000000"), + opacity=1, + xanchor="right", + yanchor="bottom", + ), + ], + xaxis1=go.layout.XAxis( + domain=[0.0, 1.0], + range=(0.0, 2.0), + showline=True, + ticks="inside", + showgrid=False, + zeroline=False, + anchor="y1", + mirror=True, + ), + yaxis1=go.layout.YAxis( + domain=[0.0, 1.0], + range=(1.0, 3.0), + showline=True, + ticks="inside", + showgrid=False, + zeroline=False, + anchor="x1", + mirror=True, + ), + ), +) diff --git a/tests/test_optional/test_matplotlylib/data/axis_scales.py b/tests/test_optional/test_matplotlylib/data/axis_scales.py new file mode 100644 index 0000000..ba8838d --- /dev/null +++ b/tests/test_optional/test_matplotlylib/data/axis_scales.py @@ -0,0 +1,56 @@ +import plotly.graph_objs as go + +D = dict(x=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], y=[10, 3, 100, 6, 45, 4, 80, 45, 3, 59]) + + +EVEN_LINEAR_SCALE = go.Figure( + data=[ + go.Scatter( + x=[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0], + y=[10.0, 3.0, 100.0, 6.0, 45.0, 4.0, 80.0, 45.0, 3.0, 59.0], + name="_line0", + mode="lines", + line=go.scatter.Line( + dash="solid", color="rgba (31, 119, 180, 1)", width=1.5 + ), + xaxis="x1", + yaxis="y1", + ) + ], + layout=go.Layout( + width=640, + height=480, + autosize=False, + margin=go.layout.Margin(l=80, r=63, b=52, t=57, pad=0), + hovermode="closest", + showlegend=False, + xaxis1=go.layout.XAxis( + domain=[0.0, 1.0], + range=[0.0, 18.0], + type="linear", + showline=True, + nticks=10, + ticks="inside", + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="y1", + side="bottom", + mirror="ticks", + ), + yaxis1=go.layout.YAxis( + domain=[0.0, 1.0], + range=[-1.8500000000000005, 195.0], + type="linear", + showline=True, + nticks=10, + ticks="inside", + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="x1", + side="left", + mirror="ticks", + ), + ), +) diff --git a/tests/test_optional/test_matplotlylib/data/bars.py b/tests/test_optional/test_matplotlylib/data/bars.py new file mode 100644 index 0000000..7a5f3cb --- /dev/null +++ b/tests/test_optional/test_matplotlylib/data/bars.py @@ -0,0 +1,174 @@ +import plotly.graph_objs as go + +D = dict( + left=[0, 1, 2, 3, 4, 5], + height=[10, 20, 50, 80, 100, 200], + bottom=[0, 1, 2, 3, 4, 5, 6], + width=[1, 4, 8, 16, 32, 64, 128], + multi_left=[0, 10, 20, 30, 40, 50], + multi_height=[1, 4, 8, 16, 32, 64], + multi_bottom=[15, 30, 45, 60, 75, 90], + multi_width=[30, 60, 20, 50, 60, 30], +) + +VERTICAL_BAR = go.Figure( + data=[ + go.Bar( + x=[0.0, 1.0, 2.0, 3.0, 4.0, 5.0], + y=[10.0, 20.0, 50.0, 80.0, 100.0, 200.0], + orientation="v", + marker=go.bar.Marker(line=dict(width=1.0), color="#1F77B4"), + opacity=1, + xaxis="x1", + yaxis="y1", + ) + ], + layout=go.Layout( + width=640, + height=480, + autosize=False, + margin=go.layout.Margin(l=80, r=63, b=52, t=57, pad=0), + hovermode="closest", + showlegend=False, + bargap=0.2, + xaxis1=go.layout.XAxis( + domain=[0.0, 1.0], + range=[-0.68999999999999995, 5.6899999999999995], + type="linear", + showline=True, + ticks="inside", + nticks=8, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="y1", + side="bottom", + mirror="ticks", + ), + yaxis1=go.layout.YAxis( + domain=[0.0, 1.0], + range=[0.0, 210.0], + type="linear", + showline=True, + ticks="inside", + nticks=10, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="x1", + side="left", + mirror="ticks", + ), + ), +) + +HORIZONTAL_BAR = go.Figure( + data=[ + go.Bar( + x=[1.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0], + y=[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], + orientation="h", + marker=go.bar.Marker(line=dict(width=1.0), color="#1F77B4"), + opacity=1, + xaxis="x1", + yaxis="y1", + ) + ], + layout=go.Layout( + width=640, + height=480, + autosize=False, + margin=go.layout.Margin(l=80, r=63, b=52, t=57, pad=0), + hovermode="closest", + showlegend=False, + bargap=0.19999999999999996, + xaxis1=go.layout.XAxis( + domain=[0.0, 1.0], + range=[0.0, 134.40000000000001], + type="linear", + showline=True, + ticks="inside", + nticks=8, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="y1", + side="bottom", + mirror="ticks", + ), + yaxis1=go.layout.YAxis( + domain=[0.0, 1.0], + range=[-0.73999999999999999, 6.7399999999999993], + type="linear", + showline=True, + ticks="inside", + nticks=9, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="x1", + side="left", + mirror="ticks", + ), + ), +) + +H_AND_V_BARS = go.Figure( + data=[ + go.Bar( + x=[0.0, 10.0, 20.0, 30.0, 40.0, 50.0], + y=[1.0, 4.0, 8.0, 16.0, 32.0, 64.0], + orientation="v", + marker=go.bar.Marker(line=dict(width=1.0), color="rgba(0, 128, 0, 0.5)"), + opacity=0.5, + xaxis="x1", + yaxis="y1", + ), + go.Bar( + x=[30.0, 60.0, 20.0, 50.0, 60.0, 30.0], + y=[15.0, 30.0, 45.0, 60.0, 75.0, 90.0], + orientation="h", + marker=go.bar.Marker(line=dict(width=1.0), color="rgba(255, 0, 0, 0.5)"), + opacity=0.5, + xaxis="x1", + yaxis="y1", + ), + ], + layout=go.Layout( + width=640, + height=480, + autosize=False, + margin=go.layout.Margin(l=80, r=63, b=52, t=57, pad=0), + hovermode="closest", + showlegend=False, + bargap=1, + xaxis1=go.layout.XAxis( + domain=[0.0, 1.0], + range=[-8.25, 63.25], + type="linear", + showline=True, + ticks="inside", + nticks=9, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="y1", + side="bottom", + mirror="ticks", + ), + yaxis1=go.layout.YAxis( + domain=[0.0, 1.0], + range=[0.0, 101.84999999999999], + type="linear", + showline=True, + ticks="inside", + nticks=7, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="x1", + side="left", + mirror="ticks", + ), + ), +) diff --git a/tests/test_optional/test_matplotlylib/data/data.py b/tests/test_optional/test_matplotlylib/data/data.py new file mode 100644 index 0000000..9845f3a --- /dev/null +++ b/tests/test_optional/test_matplotlylib/data/data.py @@ -0,0 +1,6 @@ +D = dict( + x1=[0, 1, 2, 3, 4, 5], + y1=[10, 20, 50, 80, 100, 200], + x2=[0, 1, 2, 3, 4, 5, 6], + y2=[1, 4, 8, 16, 32, 64, 128], +) diff --git a/tests/test_optional/test_matplotlylib/data/lines.py b/tests/test_optional/test_matplotlylib/data/lines.py new file mode 100644 index 0000000..0731227 --- /dev/null +++ b/tests/test_optional/test_matplotlylib/data/lines.py @@ -0,0 +1,149 @@ +import plotly.graph_objs as go + +D = dict( + x1=[0, 1, 2, 3, 4, 5], + y1=[10, 20, 50, 80, 100, 200], + x2=[0, 1, 2, 3, 4, 5, 6], + y2=[1, 4, 8, 16, 32, 64, 128], +) + +SIMPLE_LINE = go.Figure( + data=[ + go.Scatter( + x=[0.0, 1.0, 2.0, 3.0, 4.0, 5.0], + y=[10.0, 20.0, 50.0, 80.0, 100.0, 200.0], + name="simple", + mode="lines", + line=go.scatter.Line( + dash="solid", color="rgba (31, 119, 180, 1)", width=1.5 + ), + xaxis="x1", + yaxis="y1", + ) + ], + layout=go.Layout( + width=640, + height=480, + autosize=False, + margin=go.layout.Margin(l=80, r=63, b=52, t=57, pad=0), + hovermode="closest", + showlegend=False, + xaxis1=go.layout.XAxis( + domain=[0.0, 1.0], + range=[-0.25, 5.25], + type="linear", + showline=True, + ticks="inside", + nticks=8, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="y1", + side="bottom", + mirror="ticks", + ), + yaxis1=go.layout.YAxis( + domain=[0.0, 1.0], + range=[0.5, 209.5], + type="linear", + showline=True, + ticks="inside", + nticks=10, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="x1", + side="left", + mirror="ticks", + ), + ), +) + +COMPLICATED_LINE = go.Figure( + data=[ + go.Scatter( + x=[0.0, 1.0, 2.0, 3.0, 4.0, 5.0], + y=[10.0, 20.0, 50.0, 80.0, 100.0, 200.0], + name="one", + mode="markers", + marker=go.scatter.Marker( + symbol="circle", + line=dict(color="#FF0000", width=1.0), + size=10, + color="#FF0000", + opacity=0.5, + ), + xaxis="x1", + yaxis="y1", + ), + go.Scatter( + x=[0.0, 1.0, 2.0, 3.0, 4.0, 5.0], + y=[10.0, 20.0, 50.0, 80.0, 100.0, 200.0], + name="two", + mode="lines", + line=dict(dash="solid", color="rgba (0, 0, 255, 0.7)", width=2), + xaxis="x1", + yaxis="y1", + ), + go.Scatter( + x=[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], + y=[1.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0], + name="three", + mode="markers", + marker=go.scatter.Marker( + symbol="cross", + line=dict(color="#0000FF", width=2), + size=10, + color="#0000FF", + opacity=0.6, + ), + xaxis="x1", + yaxis="y1", + ), + go.Scatter( + x=[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], + y=[1.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0], + name="four", + mode="lines", + line=go.scatter.Line(dash="dash", color="rgba (255, 0, 0, 0.8)", width=2), + xaxis="x1", + yaxis="y1", + ), + ], + layout=go.Layout( + width=640, + height=480, + autosize=False, + margin=go.layout.Margin(l=80, r=63, b=52, t=57, pad=0), + hovermode="closest", + showlegend=False, + xaxis1=go.layout.XAxis( + domain=[0.0, 1.0], + range=[-0.30000000000000004, 6.2999999999999998], + type="linear", + showline=True, + ticks="inside", + nticks=9, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="y1", + side="bottom", + mirror="ticks", + ), + yaxis1=go.layout.YAxis( + domain=[0.0, 1.0], + range=[-8.9500000000000011, 209.94999999999999], + type="linear", + showline=True, + ticks="inside", + nticks=11, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="x1", + side="left", + mirror="ticks", + ), + ), +) diff --git a/tests/test_optional/test_matplotlylib/data/scatter.py b/tests/test_optional/test_matplotlylib/data/scatter.py new file mode 100644 index 0000000..2417e0a --- /dev/null +++ b/tests/test_optional/test_matplotlylib/data/scatter.py @@ -0,0 +1,130 @@ +import plotly.graph_objs as go + +D = dict( + x1=[1, 2, 2, 4, 5, 6, 1, 7, 8, 5, 3], + y1=[5, 3, 7, 2, 9, 7, 8, 4, 5, 9, 2], + x2=[-1, 1, -0.3, -0.6, 0.4, 0.8, -0.1, 0.7], + y2=[-0.5, 0.4, 0.7, -0.6, 0.3, -1, 0, 0.3], +) + + +SIMPLE_SCATTER = go.Figure( + data=[ + go.Scatter( + x=[1.0, 2.0, 2.0, 4.0, 5.0, 6.0, 1.0, 7.0, 8.0, 5.0, 3.0], + y=[5.0, 3.0, 7.0, 2.0, 9.0, 7.0, 8.0, 4.0, 5.0, 9.0, 2.0], + mode="markers", + marker=go.scatter.Marker( + symbol="circle", + line=dict(color="rgba(31,119,180,1.0)", width=1.0), + size=6.0, + color="rgba(31,119,180,1.0)", + ), + xaxis="x1", + yaxis="y1", + ) + ], + layout=go.Layout( + width=640, + height=480, + autosize=False, + margin=go.layout.Margin(l=80, r=63, b=52, t=57, pad=0), + hovermode="closest", + showlegend=False, + xaxis1=go.layout.XAxis( + domain=[0.0, 1.0], + range=[0.64334677419354847, 8.3566532258064505], + type="linear", + showline=True, + ticks="inside", + nticks=10, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="y1", + side="bottom", + mirror="ticks", + ), + yaxis1=go.layout.YAxis( + domain=[0.0, 1.0], + range=[1.6410714285714287, 9.3589285714285726], + type="linear", + showline=True, + ticks="inside", + nticks=10, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="x1", + side="left", + mirror="ticks", + ), + ), +) + +DOUBLE_SCATTER = go.Figure( + data=[ + go.Scatter( + x=[1.0, 2.0, 2.0, 4.0, 5.0, 6.0, 1.0, 7.0, 8.0, 5.0, 3.0], + y=[5.0, 3.0, 7.0, 2.0, 9.0, 7.0, 8.0, 4.0, 5.0, 9.0, 2.0], + mode="markers", + marker=go.scatter.Marker( + symbol="triangle-up", + line=dict(color="rgba(255,0,0,0.5)", width=1.0), + size=11.0, + color="rgba(255,0,0,0.5)", + ), + xaxis="x1", + yaxis="y1", + ), + go.Scatter( + x=[-1.0, 1.0, -0.3, -0.6, 0.4, 0.8, -0.1, 0.7], + y=[-0.5, 0.4, 0.7, -0.6, 0.3, -1.0, 0.0, 0.3], + mode="markers", + marker=go.scatter.Marker( + symbol="square", + line=dict(color="rgba(128,0,128,0.5)", width=1.0), + size=8.0, + color="rgba(128,0,128,0.5)", + ), + xaxis="x1", + yaxis="y1", + ), + ], + layout=go.Layout( + width=640, + height=480, + autosize=False, + margin=go.layout.Margin(l=80, r=63, b=52, t=57, pad=0), + hovermode="closest", + showlegend=False, + xaxis1=go.layout.XAxis( + domain=[0.0, 1.0], + range=[-1.5159626203173777, 8.4647578206295506], + type="linear", + showline=True, + ticks="inside", + nticks=7, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="y1", + side="bottom", + mirror="ticks", + ), + yaxis1=go.layout.YAxis( + domain=[0.0, 1.0], + range=[-1.588616071428572, 9.5198093820861693], + type="linear", + showline=True, + ticks="inside", + nticks=7, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="x1", + side="left", + mirror="ticks", + ), + ), +) diff --git a/tests/test_optional/test_matplotlylib/data/subplots.py b/tests/test_optional/test_matplotlylib/data/subplots.py new file mode 100644 index 0000000..443ac10 --- /dev/null +++ b/tests/test_optional/test_matplotlylib/data/subplots.py @@ -0,0 +1,249 @@ +import plotly.graph_objs as go + +D = dict(x1=[0, 1], y1=[1, 2]) + +BLANK_SUBPLOTS = go.Figure( + data=[ + go.Scatter( + x=[0.0, 1.0], + y=[1.0, 2.0], + name="_line0", + mode="lines", + line=go.scatter.Line(dash="solid", color="#0000FF", width=1.0), + xaxis="x1", + yaxis="y1", + ) + ], + layout=go.Layout( + width=640, + height=480, + autosize=False, + margin=go.layout.Margin(l=168, r=63, b=52, t=57, pad=0), + hovermode="closest", + showlegend=False, + xaxis1=go.layout.XAxis( + domain=[0.0, 0.13513513513513517], + range=[-0.050000000000000003, 1.05], + type="linear", + showline=True, + ticks="inside", + nticks=4, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="y1", + side="bottom", + mirror="ticks", + ), + xaxis2=go.layout.XAxis( + domain=[0.0, 0.13513513513513517], + range=[0.0, 1.0], + type="linear", + showline=True, + ticks="inside", + nticks=2, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="y2", + side="bottom", + mirror="ticks", + ), + xaxis3=go.layout.XAxis( + domain=[0.0, 0.13513513513513517], + range=[0.0, 1.0], + type="linear", + showline=True, + ticks="inside", + nticks=2, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="y3", + side="bottom", + mirror="ticks", + ), + xaxis4=go.layout.XAxis( + domain=[0.2162162162162162, 1.0], + range=[0.0, 1.0], + type="linear", + showline=True, + ticks="inside", + nticks=6, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="y4", + side="bottom", + mirror="ticks", + ), + xaxis5=go.layout.XAxis( + domain=[0.2162162162162162, 0.56756756756756754], + range=[0.0, 1.0], + type="linear", + showline=True, + ticks="inside", + nticks=3, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="y5", + side="bottom", + mirror="ticks", + ), + xaxis6=go.layout.XAxis( + domain=[0.2162162162162162, 0.78378378378378377], + range=[0.0, 1.0], + type="linear", + showline=True, + ticks="inside", + nticks=6, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="y6", + side="bottom", + mirror="ticks", + ), + xaxis7=go.layout.XAxis( + domain=[0.64864864864864857, 1.0], + range=[0.0, 1.0], + type="linear", + showline=True, + ticks="inside", + nticks=3, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="y7", + side="bottom", + mirror="ticks", + ), + xaxis8=go.layout.XAxis( + domain=[0.8648648648648648, 1.0], + range=[0.0, 1.0], + type="linear", + showline=True, + ticks="inside", + nticks=2, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="y8", + side="bottom", + mirror="ticks", + ), + yaxis1=go.layout.YAxis( + domain=[0.82758620689655171, 1.0], + range=[0.94999999999999996, 2.0499999999999998], + type="linear", + showline=True, + ticks="inside", + nticks=4, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="x1", + side="left", + mirror="ticks", + ), + yaxis2=go.layout.YAxis( + domain=[0.55172413793103448, 0.72413793103448265], + range=[0.0, 1.0], + type="linear", + showline=True, + ticks="inside", + nticks=3, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="x2", + side="left", + mirror="ticks", + ), + yaxis3=go.layout.YAxis( + domain=[0.0, 0.44827586206896547], + range=[0.0, 1.0], + type="linear", + showline=True, + ticks="inside", + nticks=6, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="x3", + side="left", + mirror="ticks", + ), + yaxis4=go.layout.YAxis( + domain=[0.82758620689655171, 1.0], + range=[0.0, 1.0], + type="linear", + showline=True, + ticks="inside", + nticks=3, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="x4", + side="left", + mirror="ticks", + ), + yaxis5=go.layout.YAxis( + domain=[0.27586206896551713, 0.72413793103448265], + range=[0.0, 1.0], + type="linear", + showline=True, + ticks="inside", + nticks=6, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="x5", + side="left", + mirror="ticks", + ), + yaxis6=go.layout.YAxis( + domain=[0.0, 0.17241379310344826], + range=[0.0, 1.0], + type="linear", + showline=True, + ticks="inside", + nticks=3, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="x6", + side="left", + mirror="ticks", + ), + yaxis7=go.layout.YAxis( + domain=[0.27586206896551713, 0.72413793103448265], + range=[0.0, 1.0], + type="linear", + showline=True, + ticks="inside", + nticks=6, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="x7", + side="left", + mirror="ticks", + ), + yaxis8=go.layout.YAxis( + domain=[0.0, 0.17241379310344826], + range=[0.0, 1.0], + type="linear", + showline=True, + ticks="inside", + nticks=3, + showgrid=False, + zeroline=False, + tickfont=dict(size=10.0), + anchor="x8", + side="left", + mirror="ticks", + ), + ), +) diff --git a/tests/test_optional/test_matplotlylib/test_annotations.py b/tests/test_optional/test_matplotlylib/test_annotations.py new file mode 100644 index 0000000..b8dda58 --- /dev/null +++ b/tests/test_optional/test_matplotlylib/test_annotations.py @@ -0,0 +1,29 @@ +import matplotlib.pyplot as plt + +from ...utils import compare_dict, strip_dict_params +from ..optional_utils import run_fig +from ..test_matplotlylib.data.annotations import ANNOTATIONS + + +def test_annotations(): + fig, ax = plt.subplots() + ax.plot([1, 2, 3], "b-") + ax.plot([3, 2, 1], "b-") + ax.text(0.001, 0.999, "top-left", transform=ax.transAxes, va="top", ha="left") + ax.text( + 0.001, 0.001, "bottom-left", transform=ax.transAxes, va="baseline", ha="left" + ) + ax.text(0.999, 0.999, "top-right", transform=ax.transAxes, va="top", ha="right") + ax.text( + 0.999, 0.001, "bottom-right", transform=ax.transAxes, va="baseline", ha="right" + ) + renderer = run_fig(fig) + for data_no, data_dict in enumerate(renderer.plotly_fig["data"]): + d1, d2 = strip_dict_params( + data_dict, ANNOTATIONS["data"][data_no], ignore=["uid"] + ) + equivalent, msg = compare_dict(d1, d2) + assert equivalent, msg + for no, note in enumerate(renderer.plotly_fig["layout"]["annotations"]): + equivalent, msg = compare_dict(note, ANNOTATIONS["layout"]["annotations"][no]) + assert equivalent, msg diff --git a/tests/test_optional/test_matplotlylib/test_axis_scales.py b/tests/test_optional/test_matplotlylib/test_axis_scales.py new file mode 100644 index 0000000..18c4969 --- /dev/null +++ b/tests/test_optional/test_matplotlylib/test_axis_scales.py @@ -0,0 +1,30 @@ +from ...utils import compare_dict, strip_dict_params +from ...test_optional.optional_utils import run_fig +from ...test_optional.test_matplotlylib.data.axis_scales import EVEN_LINEAR_SCALE + +import matplotlib.pyplot as plt + + +def test_even_linear_scale(): + fig, ax = plt.subplots() + x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + y = [10, 3, 100, 6, 45, 4, 80, 45, 3, 59] + ax.plot(x, y) + _ = ax.set_xticks(list(range(0, 20, 3)), True) + _ = ax.set_yticks(list(range(0, 200, 13)), True) + renderer = run_fig(fig) + for data_no, data_dict in enumerate(renderer.plotly_fig["data"]): + # equivalent, msg = compare_dict(data_dict.to_plotly_json(), + # EVEN_LINEAR_SCALE['data'][data_no].to_plotly_json()) + # assert equivalent, msg + d1, d2 = strip_dict_params( + data_dict, EVEN_LINEAR_SCALE["data"][data_no], ignore=["uid"] + ) + + equivalent, msg = compare_dict(d1, d2) + assert equivalent, msg + + equivalent, msg = compare_dict( + renderer.plotly_fig["layout"], EVEN_LINEAR_SCALE["layout"] + ) + assert equivalent, msg diff --git a/tests/test_optional/test_matplotlylib/test_bars.py b/tests/test_optional/test_matplotlylib/test_bars.py new file mode 100644 index 0000000..6bc6a08 --- /dev/null +++ b/tests/test_optional/test_matplotlylib/test_bars.py @@ -0,0 +1,80 @@ +from ...utils import compare_dict, strip_dict_params +from ...test_optional.optional_utils import run_fig +from ...test_optional.test_matplotlylib.data.bars import ( + D, + H_AND_V_BARS, + HORIZONTAL_BAR, + VERTICAL_BAR, +) + +import matplotlib.pyplot as plt + + +def test_vertical_bar(): + fig, ax = plt.subplots() + ax.bar(left=D["left"], height=D["height"]) + renderer = run_fig(fig) + + for data_no, data_dict in enumerate(renderer.plotly_fig["data"]): + d1, d2 = strip_dict_params( + data_dict, VERTICAL_BAR["data"][data_no], ignore=["uid"] + ) + + equivalent, msg = compare_dict(d1, d2) + assert equivalent, msg + + equivalent, msg = compare_dict( + renderer.plotly_fig["layout"], VERTICAL_BAR["layout"] + ) + assert equivalent, msg + + +def test_horizontal_bar(): + fig, ax = plt.subplots() + ax.barh(bottom=D["bottom"], width=D["width"]) + renderer = run_fig(fig) + + for data_no, data_dict in enumerate(renderer.plotly_fig["data"]): + d1, d2 = strip_dict_params( + data_dict, HORIZONTAL_BAR["data"][data_no], ignore=["uid"] + ) + + equivalent, msg = compare_dict(d1, d2) + assert equivalent, msg + + equivalent, msg = compare_dict( + renderer.plotly_fig["layout"], HORIZONTAL_BAR["layout"] + ) + assert equivalent, msg + + +def test_h_and_v_bars(): + fig, ax = plt.subplots() + ax.bar( + left=D["multi_left"], + height=D["multi_height"], + width=10, + color="green", + alpha=0.5, + ) + # changing height 10 -> 14 because ValueError if bargap not in [0, 1] + ax.barh( + bottom=D["multi_bottom"], + width=D["multi_width"], + height=14, + color="red", + alpha=0.5, + ) + renderer = run_fig(fig) + for data_no, data_dict in enumerate(renderer.plotly_fig["data"]): + d1, d2 = strip_dict_params( + data_dict, H_AND_V_BARS["data"][data_no], ignore=["uid"] + ) + + equivalent, msg = compare_dict(d1, d2) + assert equivalent, msg + + equivalent, msg = compare_dict( + renderer.plotly_fig["layout"], H_AND_V_BARS["layout"] + ) + assert equivalent, msg diff --git a/tests/test_optional/test_matplotlylib/test_data.py b/tests/test_optional/test_matplotlylib/test_data.py new file mode 100644 index 0000000..69dae00 --- /dev/null +++ b/tests/test_optional/test_matplotlylib/test_data.py @@ -0,0 +1,78 @@ +from ...test_optional.optional_utils import run_fig +from ...test_optional.test_matplotlylib.data.data import D + +import matplotlib.pyplot as plt + + +def test_line_data(): + fig, ax = plt.subplots() + ax.plot(D["x1"], D["y1"]) + renderer = run_fig(fig) + for xi, xf, yi, yf in zip( + renderer.plotly_fig["data"][0]["x"], + D["x1"], + renderer.plotly_fig["data"][0]["y"], + D["y1"], + ): + assert xi == xf, ( + str(renderer.plotly_fig["data"][0]["x"]) + " is not " + str(D["x1"]) + ) + assert yi == yf, ( + str(renderer.plotly_fig["data"][0]["y"]) + " is not " + str(D["y1"]) + ) + + +def test_lines_data(): + fig, ax = plt.subplots() + ax.plot(D["x1"], D["y1"]) + ax.plot(D["x2"], D["y2"]) + renderer = run_fig(fig) + for xi, xf, yi, yf in zip( + renderer.plotly_fig["data"][0]["x"], + D["x1"], + renderer.plotly_fig["data"][0]["y"], + D["y1"], + ): + assert xi == xf, ( + str(renderer.plotly_fig["data"][0]["x"]) + " is not " + str(D["x1"]) + ) + assert yi == yf, ( + str(renderer.plotly_fig["data"][0]["y"]) + " is not " + str(D["y1"]) + ) + for xi, xf, yi, yf in zip( + renderer.plotly_fig["data"][1]["x"], + D["x2"], + renderer.plotly_fig["data"][1]["y"], + D["y2"], + ): + assert xi == xf, ( + str(renderer.plotly_fig["data"][1]["x"]) + " is not " + str(D["x2"]) + ) + assert yi == yf, ( + str(renderer.plotly_fig["data"][0]["y"]) + " is not " + str(D["y2"]) + ) + + +def test_bar_data(): + fig, ax = plt.subplots() + ax.bar(D["x1"], D["y1"]) + renderer = run_fig(fig) + for yi, yf in zip(renderer.plotly_fig["data"][0]["y"], D["y1"]): + assert yi == yf, ( + str(renderer.plotly_fig["data"][0]["y"]) + " is not " + str(D["y1"]) + ) + + +def test_bars_data(): + fig, ax = plt.subplots() + ax.bar(D["x1"], D["y1"], color="r") + ax.barh(D["x2"], D["y2"], color="b") + renderer = run_fig(fig) + for yi, yf in zip(renderer.plotly_fig["data"][0]["y"], D["y1"]): + assert yi == yf, ( + str(renderer.plotly_fig["data"][0]["y"]) + " is not " + str(D["y1"]) + ) + for xi, yf in zip(renderer.plotly_fig["data"][1]["x"], D["y2"]): + assert xi == yf, ( + str(renderer.plotly_fig["data"][1]["x"]) + " is not " + str(D["y2"]) + ) diff --git a/tests/test_optional/test_matplotlylib/test_date_times.py b/tests/test_optional/test_matplotlylib/test_date_times.py new file mode 100644 index 0000000..350aad9 --- /dev/null +++ b/tests/test_optional/test_matplotlylib/test_date_times.py @@ -0,0 +1,67 @@ +import datetime +import random +from unittest import TestCase + +import pandas as pd + +from matplotlylib import mpl_to_plotly + +from matplotlib.dates import date2num +import matplotlib.pyplot as plt + + +class TestDateTimes(TestCase): + def test_normal_mpl_dates(self): + datetime_format = "%Y-%m-%d %H:%M:%S" + y = [1, 2, 3, 4] + date_strings = [ + "2010-01-04 00:00:00", + "2010-01-04 10:00:00", + "2010-01-04 23:00:59", + "2010-01-05 00:00:00", + ] + + # 1. create datetimes from the strings + dates = [ + datetime.datetime.strptime(date_string, datetime_format) + for date_string in date_strings + ] + + # 2. create the mpl_dates from these datetimes + mpl_dates = date2num(dates) + + # make a figure in mpl + fig, ax = plt.subplots() + ax.plot_date(mpl_dates, y) + + # convert this figure to plotly's graph_objs + pfig = mpl_to_plotly(fig) + + print(date_strings) + print(pfig["data"][0]["x"]) + # we use the same format here, so we expect equality here + self.assertEqual(fig.axes[0].lines[0].get_xydata()[0][0], 7.33776000e05) + self.assertEqual(tuple(pfig["data"][0]["x"]), tuple(date_strings)) + + def test_pandas_time_series_date_formatter(self): + ndays = 3 + x = pd.date_range("1/1/2001", periods=ndays, freq="D") + y = [random.randint(0, 10) for i in range(ndays)] + s = pd.DataFrame(y, columns=["a"]) + + s["Date"] = x + s.plot(x="Date") + + fig = plt.gcf() + pfig = mpl_to_plotly(fig) + + expected_x = ( + "2001-01-01 00:00:00", + "2001-01-02 00:00:00", + "2001-01-03 00:00:00", + ) + expected_x0 = 11323.0 # this is floating point days since epoch + + x0 = fig.axes[0].lines[0].get_xydata()[0][0] + self.assertEqual(x0, expected_x0) + self.assertEqual(pfig["data"][0]["x"], expected_x) diff --git a/tests/test_optional/test_matplotlylib/test_lines.py b/tests/test_optional/test_matplotlylib/test_lines.py new file mode 100644 index 0000000..c41dd84 --- /dev/null +++ b/tests/test_optional/test_matplotlylib/test_lines.py @@ -0,0 +1,53 @@ +from ...utils import compare_dict, strip_dict_params +from ...test_optional.optional_utils import run_fig +from ...test_optional.test_matplotlylib.data.lines import ( + COMPLICATED_LINE, + D, + SIMPLE_LINE, +) + +import matplotlib.pyplot as plt + + +def test_simple_line(): + fig, ax = plt.subplots() + ax.plot(D["x1"], D["y1"], label="simple") + renderer = run_fig(fig) + for data_no, data_dict in enumerate(renderer.plotly_fig["data"]): + d1, d2 = strip_dict_params( + data_dict, SIMPLE_LINE["data"][data_no], ignore=["uid"] + ) + + equivalent, msg = compare_dict(d1, d2) + assert equivalent, msg + equivalent, msg = compare_dict(renderer.plotly_fig["layout"], SIMPLE_LINE["layout"]) + assert equivalent, msg + + +def test_complicated_line(): + fig, ax = plt.subplots() + ax.plot(D["x1"], D["y1"], "ro", markersize=10, alpha=0.5, label="one") + ax.plot(D["x1"], D["y1"], "-b", linewidth=2, alpha=0.7, label="two") + ax.plot( + D["x2"], + D["y2"], + "b+", + markeredgewidth=2, + markersize=10, + alpha=0.6, + label="three", + ) + ax.plot(D["x2"], D["y2"], "--r", linewidth=2, alpha=0.8, label="four") + renderer = run_fig(fig) + for data_no, data_dict in enumerate(renderer.plotly_fig["data"]): + d1, d2 = strip_dict_params( + data_dict, COMPLICATED_LINE["data"][data_no], ignore=["uid"] + ) + + equivalent, msg = compare_dict(d1, d2) + assert equivalent, msg + + equivalent, msg = compare_dict( + renderer.plotly_fig["layout"], COMPLICATED_LINE["layout"] + ) + assert equivalent, msg diff --git a/tests/test_optional/test_matplotlylib/test_scatter.py b/tests/test_optional/test_matplotlylib/test_scatter.py new file mode 100644 index 0000000..88ef11c --- /dev/null +++ b/tests/test_optional/test_matplotlylib/test_scatter.py @@ -0,0 +1,48 @@ +from ...utils import compare_dict, strip_dict_params +from ...test_optional.optional_utils import run_fig +from ...test_optional.test_matplotlylib.data.scatter import ( + D, + DOUBLE_SCATTER, + SIMPLE_SCATTER, +) + +import matplotlib.pyplot as plt + + +def test_simple_scatter(): + fig, ax = plt.subplots() + ax.scatter(D["x1"], D["y1"]) + renderer = run_fig(fig) + for data_no, data_dict in enumerate(renderer.plotly_fig["data"]): + d1, d2 = strip_dict_params( + data_dict, SIMPLE_SCATTER["data"][data_no], ignore=["uid"] + ) + print(d1) + print("\n") + print(d2) + assert d1 == d2 + + equivalent, msg = compare_dict( + renderer.plotly_fig["layout"], SIMPLE_SCATTER["layout"] + ) + assert equivalent, msg + + +def test_double_scatter(): + fig, ax = plt.subplots() + ax.scatter(D["x1"], D["y1"], color="red", s=121, marker="^", alpha=0.5) + ax.scatter(D["x2"], D["y2"], color="purple", s=64, marker="s", alpha=0.5) + renderer = run_fig(fig) + for data_no, data_dict in enumerate(renderer.plotly_fig["data"]): + d1, d2 = strip_dict_params( + data_dict, DOUBLE_SCATTER["data"][data_no], ignore=["uid"] + ) + print(d1) + print("\n") + print(d2) + assert d1 == d2 + + equivalent, msg = compare_dict( + renderer.plotly_fig["layout"], DOUBLE_SCATTER["layout"] + ) + assert equivalent, msg diff --git a/tests/test_optional/test_matplotlylib/test_subplots.py b/tests/test_optional/test_matplotlylib/test_subplots.py new file mode 100644 index 0000000..bf74b0e --- /dev/null +++ b/tests/test_optional/test_matplotlylib/test_subplots.py @@ -0,0 +1,33 @@ +from ...utils import compare_dict, strip_dict_params +from ...test_optional.optional_utils import run_fig +from ...test_optional.test_matplotlylib.data.subplots import D, BLANK_SUBPLOTS + +from matplotlib.gridspec import GridSpec +import matplotlib.pyplot as plt + + +def test_blank_subplots(): + fig = plt.figure() + gs = GridSpec(4, 6) + ax1 = fig.add_subplot(gs[0, 1]) + ax1.plot(D["x1"], D["y1"]) + fig.add_subplot(gs[1, 1]) + fig.add_subplot(gs[2:, 1]) + fig.add_subplot(gs[0, 2:]) + fig.add_subplot(gs[1:3, 2:4]) + fig.add_subplot(gs[3, 2:5]) + fig.add_subplot(gs[1:3, 4:]) + fig.add_subplot(gs[3, 5]) + gs.update(hspace=0.6, wspace=0.6) + renderer = run_fig(fig) + + for data_no, data_dict in enumerate(renderer.plotly_fig["data"]): + d1, d2 = strip_dict_params( + data_dict, BLANK_SUBPLOTS["data"][data_no], ignore=["uid"] + ) + equivalent, msg = compare_dict(d1, d2) + + equivalent, msg = compare_dict( + renderer.plotly_fig["layout"], BLANK_SUBPLOTS["layout"] + ) + assert equivalent, msg diff --git a/tests/utils.py b/tests/utils.py new file mode 100644 index 0000000..89ffb9c --- /dev/null +++ b/tests/utils.py @@ -0,0 +1,97 @@ +import copy +from numbers import Number as Num +from unittest import TestCase +import plotly.io as pio + + +class TestCaseNoTemplate(TestCase): + def setUp(self): + pio.templates.default = None + + def tearDown(self): + pio.templates.default = "plotly" + + +def compare_dict(dict1, dict2, equivalent=True, msg="", tol=10e-8): + for key in dict1: + if key not in dict2: + return ( + False, + "{0} should be {1}".format(list(dict1.keys()), list(dict2.keys())), + ) + for key in dict1: + if isinstance(dict1[key], dict): + equivalent, msg = compare_dict(dict1[key], dict2[key], tol=tol) + elif isinstance(dict1[key], Num) and isinstance(dict2[key], Num): + if not comp_nums(dict1[key], dict2[key], tol): + return ( + False, + "['{0}'] = {1} should be {2}".format(key, dict1[key], dict2[key]), + ) + elif is_num_list(dict1[key]) and is_num_list(dict2[key]): + if not comp_num_list(dict1[key], dict2[key], tol): + return ( + False, + "['{0}'] = {1} should be {2}".format(key, dict1[key], dict2[key]), + ) + elif not (dict1[key] == dict2[key]): + return ( + False, + "['{0}'] = {1} should be {2}".format(key, dict1[key], dict2[key]), + ) + if not equivalent: + return False, "['{0}']".format(key) + msg + return equivalent, msg + + +def strip_dict_params(d1, d2, ignore=["uid"]): + """ + Helper function for assert_dict_equal + + Nearly duplicate of assert_fig_equal in tests/test_optional/optional_utils.py + Removes `ignore` params from d1 and/or d2 if they exist + then returns stripped dictionaries + + :param (list|tuple) ignore: sequence of key names as + strings that are removed from both d1 and d2 if + they exist + """ + # deep copy d1 and d2 + if "to_plotly_json" in dir(d1): + d1_copy = copy.deepcopy(d1.to_plotly_json()) + else: + d1_copy = copy.deepcopy(d1) + + if "to_plotly_json" in dir(d2): + d2_copy = copy.deepcopy(d2.to_plotly_json()) + else: + d2_copy = copy.deepcopy(d2) + + for key in ignore: + if key in d1_copy.keys(): + del d1_copy[key] + if key in d2_copy.keys(): + del d2_copy[key] + + return d1_copy, d2_copy + + +def comp_nums(num1, num2, tol=10e-8): + return abs(num1 - num2) < tol + + +def comp_num_list(list1, list2, tol=10e-8): + for item1, item2 in zip(list1, list2): + if not comp_nums(item1, item2, tol): + return False + return True + + +def is_num_list(item): + try: + for thing in item: + if not isinstance(thing, Num): + raise TypeError + except TypeError: + return False + return True From fdf3bbb375bf7141fbe1edf422bf2ec9d04b95ac Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Fri, 4 Dec 2026 01:13:39 +0000 Subject: [PATCH 02/23] Remove the unused NumpyTestUtilsMixin test helper Nothing uses NumpyTestUtilsMixin or its assert_fig_equal and assert_dict_equal methods. Remove it, the imports only it used, and the references to it in the strip_dict_params docstring. --- tests/test_optional/optional_utils.py | 105 -------------------------- tests/utils.py | 3 - 2 files changed, 108 deletions(-) diff --git a/tests/test_optional/optional_utils.py b/tests/test_optional/optional_utils.py index a67f3d3..4268af3 100644 --- a/tests/test_optional/optional_utils.py +++ b/tests/test_optional/optional_utils.py @@ -1,10 +1,3 @@ -import numpy as np - -from ..utils import is_num_list -from plotly.utils import get_by_path, node_generator - -import copy - import matplotlib # Force matplotlib to not use any Xwindows backend. @@ -18,101 +11,3 @@ def run_fig(fig): print(exporter) exporter.run(fig) return renderer - - -class NumpyTestUtilsMixin(object): - """Provides some helper functions to make testing easier.""" - - def _format_path(self, path): - str_path = [repr(p) for p in path] - return "[" + "][".join(sp for sp in str_path) + "]" - - def assert_fig_equal(self, d1, d2, msg=None, ignore=["uid"]): - """ - Helper function for assert_dict_equal - - By default removes uid from d1 and/or d2 if present - then calls assert_dict_equal. - - :param (list|tuple) ignore: sequence of key names as - strings that are removed from both d1 and d2 if - they exist - """ - # deep copy d1 and d2 - if "to_plotly_json" in dir(d1): - d1_copy = copy.deepcopy(d1.to_plotly_json()) - else: - d1_copy = copy.deepcopy(d1) - - if "to_plotly_json" in dir(d2): - d2_copy = copy.deepcopy(d2.to_plotly_json()) - else: - d2_copy = copy.deepcopy(d2) - - for key in ignore: - if key in d1_copy.keys(): - del d1_copy[key] - if key in d2_copy.keys(): - del d2_copy[key] - - self.assert_dict_equal(d1_copy, d2_copy, msg=None) - - def assert_dict_equal(self, d1, d2, msg=None): - """ - Uses `np.allclose()` on number arrays. - - :raises: (AssertionError) Using TestCase's self.failureException - - """ - self.assertIsInstance(d1, dict, "First argument is not a dictionary") - self.assertIsInstance(d2, dict, "Second argument is not a dictionary") - - for node, path in node_generator(d1): - # first check that this sub-dict is contained in both dicts - try: - comp_node = get_by_path(d2, path) - except (KeyError, IndexError): - standard_msg = "Path {} exists in dict 1, but not dict 2.".format(path) - self.fail(self._formatMessage(msg, standard_msg)) - self.assertIsInstance( - comp_node, dict, "Value at path {} is not a dict.".format(path) - ) - - # check that each key in the first is contained in the second - for key, val in node.items(): - if isinstance(val, dict): - continue # this gets tested as its own node - - # check that the values at this key are equal - val_path = path + (key,) - try: - comp_val = comp_node[key] - except KeyError: - standard_msg = "Path {} exists in dict 1, but not dict 2.".format( - self._format_path(val_path) - ) - self.fail(self._formatMessage(msg, standard_msg)) - - if isinstance(val, np.ndarray) or isinstance(comp_val, np.ndarray): - if np.array_equal(val, comp_val): - continue - elif val == comp_val: - continue - - if is_num_list(val) and is_num_list(comp_val): - if np.allclose(val, comp_val): - continue - - standard_msg = "Value comparison failed at path {}.\n{} != {}".format( - self._format_path(val_path), val, comp_val - ) - self.fail(self._formatMessage(msg, standard_msg)) - - # finally, check that keys in the second are in the first - for key in comp_node: - val_path = path + (key,) - if key not in node: - standard_msg = "Path {} exists in dict 2, but not dict 1.".format( - self._format_path(val_path) - ) - self.fail(self._formatMessage(msg, standard_msg)) diff --git a/tests/utils.py b/tests/utils.py index 89ffb9c..351c42f 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -46,9 +46,6 @@ def compare_dict(dict1, dict2, equivalent=True, msg="", tol=10e-8): def strip_dict_params(d1, d2, ignore=["uid"]): """ - Helper function for assert_dict_equal - - Nearly duplicate of assert_fig_equal in tests/test_optional/optional_utils.py Removes `ignore` params from d1 and/or d2 if they exist then returns stripped dictionaries From b6efd1719255ce3c856911657cbf2359402d0822 Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Fri, 4 Dec 2026 01:14:00 +0000 Subject: [PATCH 03/23] Remove the unused TestCaseNoTemplate test helper Nothing uses TestCaseNoTemplate. Remove it and the imports only it used. --- tests/utils.py | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/tests/utils.py b/tests/utils.py index 351c42f..d0024f7 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -1,15 +1,5 @@ import copy from numbers import Number as Num -from unittest import TestCase -import plotly.io as pio - - -class TestCaseNoTemplate(TestCase): - def setUp(self): - pio.templates.default = None - - def tearDown(self): - pio.templates.default = "plotly" def compare_dict(dict1, dict2, equivalent=True, msg="", tol=10e-8): From 600f81b90024a0d285b934d467ab3e76683d05fc Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Fri, 4 Dec 2026 01:18:28 +0000 Subject: [PATCH 04/23] Remove the setup_package hook that pytest never calls setup_package is a nose hook from when plotly.py ran its tests with nose. pytest does not call it (checked with pytest 7.4.4 and 9.2.0), so it has not silenced any warnings since plotly.py switched to pytest. Keep the file empty, since it still marks the directory as a package. --- tests/test_optional/test_matplotlylib/__init__.py | 5 ----- 1 file changed, 5 deletions(-) diff --git a/tests/test_optional/test_matplotlylib/__init__.py b/tests/test_optional/test_matplotlylib/__init__.py index e1565c8..e69de29 100644 --- a/tests/test_optional/test_matplotlylib/__init__.py +++ b/tests/test_optional/test_matplotlylib/__init__.py @@ -1,5 +0,0 @@ -import warnings - - -def setup_package(): - warnings.filterwarnings("ignore") From b8d1685f5343a34f0473ea2da777aa2ea78604fa Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Fri, 4 Dec 2026 01:28:36 +0000 Subject: [PATCH 05/23] Remove redundant matplotlib backend setup from ported tests tests/__init__.py already selects the Agg backend, and Python runs it before importing anything under tests/, so the matplotlib.use("Agg") calls in tests/test_optional/__init__.py and optional_utils.py have no effect. The try/except around the first one also guarded against matplotlib being missing, which was possible in plotly.py but not here. Keep the now-empty __init__.py, since it still marks the directory as a package. --- tests/test_optional/__init__.py | 7 ------- tests/test_optional/optional_utils.py | 4 ---- 2 files changed, 11 deletions(-) diff --git a/tests/test_optional/__init__.py b/tests/test_optional/__init__.py index c127f04..e69de29 100644 --- a/tests/test_optional/__init__.py +++ b/tests/test_optional/__init__.py @@ -1,7 +0,0 @@ -try: - # Set matplotlib backend once here - import matplotlib - - matplotlib.use("Agg") -except Exception: - pass diff --git a/tests/test_optional/optional_utils.py b/tests/test_optional/optional_utils.py index 4268af3..695d314 100644 --- a/tests/test_optional/optional_utils.py +++ b/tests/test_optional/optional_utils.py @@ -1,7 +1,3 @@ -import matplotlib - -# Force matplotlib to not use any Xwindows backend. -matplotlib.use("Agg") from matplotlylib import Exporter, PlotlyRenderer From ab750f46e9b3bcadcd5307a1d7443fc4bd51bb32 Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Fri, 4 Dec 2026 01:31:57 +0000 Subject: [PATCH 06/23] Remove debugging leftovers from the ported tests - print(exporter) in run_fig, which only printed the object's default repr - print calls in test_scatter and test_date_times. pytest already shows the differing values when the assertions after them fail. - A commented-out assertion in test_axis_scales - The unused `_ =` assignments of set_xticks and set_yticks in test_axis_scales. The calls themselves stay, since they set up the figure under test. --- tests/test_optional/optional_utils.py | 1 - tests/test_optional/test_matplotlylib/test_axis_scales.py | 7 ++----- tests/test_optional/test_matplotlylib/test_date_times.py | 2 -- tests/test_optional/test_matplotlylib/test_scatter.py | 6 ------ 4 files changed, 2 insertions(+), 14 deletions(-) diff --git a/tests/test_optional/optional_utils.py b/tests/test_optional/optional_utils.py index 695d314..1e947cd 100644 --- a/tests/test_optional/optional_utils.py +++ b/tests/test_optional/optional_utils.py @@ -4,6 +4,5 @@ def run_fig(fig): renderer = PlotlyRenderer() exporter = Exporter(renderer) - print(exporter) exporter.run(fig) return renderer diff --git a/tests/test_optional/test_matplotlylib/test_axis_scales.py b/tests/test_optional/test_matplotlylib/test_axis_scales.py index 18c4969..515dd6c 100644 --- a/tests/test_optional/test_matplotlylib/test_axis_scales.py +++ b/tests/test_optional/test_matplotlylib/test_axis_scales.py @@ -10,13 +10,10 @@ def test_even_linear_scale(): x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] y = [10, 3, 100, 6, 45, 4, 80, 45, 3, 59] ax.plot(x, y) - _ = ax.set_xticks(list(range(0, 20, 3)), True) - _ = ax.set_yticks(list(range(0, 200, 13)), True) + ax.set_xticks(list(range(0, 20, 3)), True) + ax.set_yticks(list(range(0, 200, 13)), True) renderer = run_fig(fig) for data_no, data_dict in enumerate(renderer.plotly_fig["data"]): - # equivalent, msg = compare_dict(data_dict.to_plotly_json(), - # EVEN_LINEAR_SCALE['data'][data_no].to_plotly_json()) - # assert equivalent, msg d1, d2 = strip_dict_params( data_dict, EVEN_LINEAR_SCALE["data"][data_no], ignore=["uid"] ) diff --git a/tests/test_optional/test_matplotlylib/test_date_times.py b/tests/test_optional/test_matplotlylib/test_date_times.py index 350aad9..fefdfaf 100644 --- a/tests/test_optional/test_matplotlylib/test_date_times.py +++ b/tests/test_optional/test_matplotlylib/test_date_times.py @@ -37,8 +37,6 @@ def test_normal_mpl_dates(self): # convert this figure to plotly's graph_objs pfig = mpl_to_plotly(fig) - print(date_strings) - print(pfig["data"][0]["x"]) # we use the same format here, so we expect equality here self.assertEqual(fig.axes[0].lines[0].get_xydata()[0][0], 7.33776000e05) self.assertEqual(tuple(pfig["data"][0]["x"]), tuple(date_strings)) diff --git a/tests/test_optional/test_matplotlylib/test_scatter.py b/tests/test_optional/test_matplotlylib/test_scatter.py index 88ef11c..64d4984 100644 --- a/tests/test_optional/test_matplotlylib/test_scatter.py +++ b/tests/test_optional/test_matplotlylib/test_scatter.py @@ -17,9 +17,6 @@ def test_simple_scatter(): d1, d2 = strip_dict_params( data_dict, SIMPLE_SCATTER["data"][data_no], ignore=["uid"] ) - print(d1) - print("\n") - print(d2) assert d1 == d2 equivalent, msg = compare_dict( @@ -37,9 +34,6 @@ def test_double_scatter(): d1, d2 = strip_dict_params( data_dict, DOUBLE_SCATTER["data"][data_no], ignore=["uid"] ) - print(d1) - print("\n") - print(d2) assert d1 == d2 equivalent, msg = compare_dict( From 15cea18c45e0d2b039efd36a7806e48ff0f199eb Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Fri, 4 Dec 2026 01:38:25 +0000 Subject: [PATCH 07/23] Call mpl_to_plotly in the ported tests The ported tests converted figures with run_fig, a test helper that builds a PlotlyRenderer, runs an Exporter on it and returns the renderer. mpl_to_plotly does the same with its default arguments and returns the figure, so call it directly, as test_renderer does, and remove optional_utils.py, which only held run_fig. --- tests/test_optional/optional_utils.py | 8 --- .../test_matplotlylib/test_annotations.py | 8 +-- .../test_matplotlylib/test_axis_scales.py | 10 ++- .../test_matplotlylib/test_bars.py | 26 +++----- .../test_matplotlylib/test_data.py | 64 +++++++------------ .../test_matplotlylib/test_lines.py | 16 ++--- .../test_matplotlylib/test_scatter.py | 18 ++---- .../test_matplotlylib/test_subplots.py | 10 ++- 8 files changed, 59 insertions(+), 101 deletions(-) delete mode 100644 tests/test_optional/optional_utils.py diff --git a/tests/test_optional/optional_utils.py b/tests/test_optional/optional_utils.py deleted file mode 100644 index 1e947cd..0000000 --- a/tests/test_optional/optional_utils.py +++ /dev/null @@ -1,8 +0,0 @@ -from matplotlylib import Exporter, PlotlyRenderer - - -def run_fig(fig): - renderer = PlotlyRenderer() - exporter = Exporter(renderer) - exporter.run(fig) - return renderer diff --git a/tests/test_optional/test_matplotlylib/test_annotations.py b/tests/test_optional/test_matplotlylib/test_annotations.py index b8dda58..748f81d 100644 --- a/tests/test_optional/test_matplotlylib/test_annotations.py +++ b/tests/test_optional/test_matplotlylib/test_annotations.py @@ -1,7 +1,7 @@ import matplotlib.pyplot as plt from ...utils import compare_dict, strip_dict_params -from ..optional_utils import run_fig +from matplotlylib import mpl_to_plotly from ..test_matplotlylib.data.annotations import ANNOTATIONS @@ -17,13 +17,13 @@ def test_annotations(): ax.text( 0.999, 0.001, "bottom-right", transform=ax.transAxes, va="baseline", ha="right" ) - renderer = run_fig(fig) - for data_no, data_dict in enumerate(renderer.plotly_fig["data"]): + plotly_fig = mpl_to_plotly(fig) + for data_no, data_dict in enumerate(plotly_fig["data"]): d1, d2 = strip_dict_params( data_dict, ANNOTATIONS["data"][data_no], ignore=["uid"] ) equivalent, msg = compare_dict(d1, d2) assert equivalent, msg - for no, note in enumerate(renderer.plotly_fig["layout"]["annotations"]): + for no, note in enumerate(plotly_fig["layout"]["annotations"]): equivalent, msg = compare_dict(note, ANNOTATIONS["layout"]["annotations"][no]) assert equivalent, msg diff --git a/tests/test_optional/test_matplotlylib/test_axis_scales.py b/tests/test_optional/test_matplotlylib/test_axis_scales.py index 515dd6c..5a78fb2 100644 --- a/tests/test_optional/test_matplotlylib/test_axis_scales.py +++ b/tests/test_optional/test_matplotlylib/test_axis_scales.py @@ -1,5 +1,5 @@ from ...utils import compare_dict, strip_dict_params -from ...test_optional.optional_utils import run_fig +from matplotlylib import mpl_to_plotly from ...test_optional.test_matplotlylib.data.axis_scales import EVEN_LINEAR_SCALE import matplotlib.pyplot as plt @@ -12,8 +12,8 @@ def test_even_linear_scale(): ax.plot(x, y) ax.set_xticks(list(range(0, 20, 3)), True) ax.set_yticks(list(range(0, 200, 13)), True) - renderer = run_fig(fig) - for data_no, data_dict in enumerate(renderer.plotly_fig["data"]): + plotly_fig = mpl_to_plotly(fig) + for data_no, data_dict in enumerate(plotly_fig["data"]): d1, d2 = strip_dict_params( data_dict, EVEN_LINEAR_SCALE["data"][data_no], ignore=["uid"] ) @@ -21,7 +21,5 @@ def test_even_linear_scale(): equivalent, msg = compare_dict(d1, d2) assert equivalent, msg - equivalent, msg = compare_dict( - renderer.plotly_fig["layout"], EVEN_LINEAR_SCALE["layout"] - ) + equivalent, msg = compare_dict(plotly_fig["layout"], EVEN_LINEAR_SCALE["layout"]) assert equivalent, msg diff --git a/tests/test_optional/test_matplotlylib/test_bars.py b/tests/test_optional/test_matplotlylib/test_bars.py index 6bc6a08..43311e1 100644 --- a/tests/test_optional/test_matplotlylib/test_bars.py +++ b/tests/test_optional/test_matplotlylib/test_bars.py @@ -1,5 +1,5 @@ from ...utils import compare_dict, strip_dict_params -from ...test_optional.optional_utils import run_fig +from matplotlylib import mpl_to_plotly from ...test_optional.test_matplotlylib.data.bars import ( D, H_AND_V_BARS, @@ -13,9 +13,9 @@ def test_vertical_bar(): fig, ax = plt.subplots() ax.bar(left=D["left"], height=D["height"]) - renderer = run_fig(fig) + plotly_fig = mpl_to_plotly(fig) - for data_no, data_dict in enumerate(renderer.plotly_fig["data"]): + for data_no, data_dict in enumerate(plotly_fig["data"]): d1, d2 = strip_dict_params( data_dict, VERTICAL_BAR["data"][data_no], ignore=["uid"] ) @@ -23,18 +23,16 @@ def test_vertical_bar(): equivalent, msg = compare_dict(d1, d2) assert equivalent, msg - equivalent, msg = compare_dict( - renderer.plotly_fig["layout"], VERTICAL_BAR["layout"] - ) + equivalent, msg = compare_dict(plotly_fig["layout"], VERTICAL_BAR["layout"]) assert equivalent, msg def test_horizontal_bar(): fig, ax = plt.subplots() ax.barh(bottom=D["bottom"], width=D["width"]) - renderer = run_fig(fig) + plotly_fig = mpl_to_plotly(fig) - for data_no, data_dict in enumerate(renderer.plotly_fig["data"]): + for data_no, data_dict in enumerate(plotly_fig["data"]): d1, d2 = strip_dict_params( data_dict, HORIZONTAL_BAR["data"][data_no], ignore=["uid"] ) @@ -42,9 +40,7 @@ def test_horizontal_bar(): equivalent, msg = compare_dict(d1, d2) assert equivalent, msg - equivalent, msg = compare_dict( - renderer.plotly_fig["layout"], HORIZONTAL_BAR["layout"] - ) + equivalent, msg = compare_dict(plotly_fig["layout"], HORIZONTAL_BAR["layout"]) assert equivalent, msg @@ -65,8 +61,8 @@ def test_h_and_v_bars(): color="red", alpha=0.5, ) - renderer = run_fig(fig) - for data_no, data_dict in enumerate(renderer.plotly_fig["data"]): + plotly_fig = mpl_to_plotly(fig) + for data_no, data_dict in enumerate(plotly_fig["data"]): d1, d2 = strip_dict_params( data_dict, H_AND_V_BARS["data"][data_no], ignore=["uid"] ) @@ -74,7 +70,5 @@ def test_h_and_v_bars(): equivalent, msg = compare_dict(d1, d2) assert equivalent, msg - equivalent, msg = compare_dict( - renderer.plotly_fig["layout"], H_AND_V_BARS["layout"] - ) + equivalent, msg = compare_dict(plotly_fig["layout"], H_AND_V_BARS["layout"]) assert equivalent, msg diff --git a/tests/test_optional/test_matplotlylib/test_data.py b/tests/test_optional/test_matplotlylib/test_data.py index 69dae00..2ffa7d7 100644 --- a/tests/test_optional/test_matplotlylib/test_data.py +++ b/tests/test_optional/test_matplotlylib/test_data.py @@ -1,4 +1,4 @@ -from ...test_optional.optional_utils import run_fig +from matplotlylib import mpl_to_plotly from ...test_optional.test_matplotlylib.data.data import D import matplotlib.pyplot as plt @@ -7,72 +7,54 @@ def test_line_data(): fig, ax = plt.subplots() ax.plot(D["x1"], D["y1"]) - renderer = run_fig(fig) + plotly_fig = mpl_to_plotly(fig) for xi, xf, yi, yf in zip( - renderer.plotly_fig["data"][0]["x"], + plotly_fig["data"][0]["x"], D["x1"], - renderer.plotly_fig["data"][0]["y"], + plotly_fig["data"][0]["y"], D["y1"], ): - assert xi == xf, ( - str(renderer.plotly_fig["data"][0]["x"]) + " is not " + str(D["x1"]) - ) - assert yi == yf, ( - str(renderer.plotly_fig["data"][0]["y"]) + " is not " + str(D["y1"]) - ) + assert xi == xf, str(plotly_fig["data"][0]["x"]) + " is not " + str(D["x1"]) + assert yi == yf, str(plotly_fig["data"][0]["y"]) + " is not " + str(D["y1"]) def test_lines_data(): fig, ax = plt.subplots() ax.plot(D["x1"], D["y1"]) ax.plot(D["x2"], D["y2"]) - renderer = run_fig(fig) + plotly_fig = mpl_to_plotly(fig) for xi, xf, yi, yf in zip( - renderer.plotly_fig["data"][0]["x"], + plotly_fig["data"][0]["x"], D["x1"], - renderer.plotly_fig["data"][0]["y"], + plotly_fig["data"][0]["y"], D["y1"], ): - assert xi == xf, ( - str(renderer.plotly_fig["data"][0]["x"]) + " is not " + str(D["x1"]) - ) - assert yi == yf, ( - str(renderer.plotly_fig["data"][0]["y"]) + " is not " + str(D["y1"]) - ) + assert xi == xf, str(plotly_fig["data"][0]["x"]) + " is not " + str(D["x1"]) + assert yi == yf, str(plotly_fig["data"][0]["y"]) + " is not " + str(D["y1"]) for xi, xf, yi, yf in zip( - renderer.plotly_fig["data"][1]["x"], + plotly_fig["data"][1]["x"], D["x2"], - renderer.plotly_fig["data"][1]["y"], + plotly_fig["data"][1]["y"], D["y2"], ): - assert xi == xf, ( - str(renderer.plotly_fig["data"][1]["x"]) + " is not " + str(D["x2"]) - ) - assert yi == yf, ( - str(renderer.plotly_fig["data"][0]["y"]) + " is not " + str(D["y2"]) - ) + assert xi == xf, str(plotly_fig["data"][1]["x"]) + " is not " + str(D["x2"]) + assert yi == yf, str(plotly_fig["data"][0]["y"]) + " is not " + str(D["y2"]) def test_bar_data(): fig, ax = plt.subplots() ax.bar(D["x1"], D["y1"]) - renderer = run_fig(fig) - for yi, yf in zip(renderer.plotly_fig["data"][0]["y"], D["y1"]): - assert yi == yf, ( - str(renderer.plotly_fig["data"][0]["y"]) + " is not " + str(D["y1"]) - ) + plotly_fig = mpl_to_plotly(fig) + for yi, yf in zip(plotly_fig["data"][0]["y"], D["y1"]): + assert yi == yf, str(plotly_fig["data"][0]["y"]) + " is not " + str(D["y1"]) def test_bars_data(): fig, ax = plt.subplots() ax.bar(D["x1"], D["y1"], color="r") ax.barh(D["x2"], D["y2"], color="b") - renderer = run_fig(fig) - for yi, yf in zip(renderer.plotly_fig["data"][0]["y"], D["y1"]): - assert yi == yf, ( - str(renderer.plotly_fig["data"][0]["y"]) + " is not " + str(D["y1"]) - ) - for xi, yf in zip(renderer.plotly_fig["data"][1]["x"], D["y2"]): - assert xi == yf, ( - str(renderer.plotly_fig["data"][1]["x"]) + " is not " + str(D["y2"]) - ) + plotly_fig = mpl_to_plotly(fig) + for yi, yf in zip(plotly_fig["data"][0]["y"], D["y1"]): + assert yi == yf, str(plotly_fig["data"][0]["y"]) + " is not " + str(D["y1"]) + for xi, yf in zip(plotly_fig["data"][1]["x"], D["y2"]): + assert xi == yf, str(plotly_fig["data"][1]["x"]) + " is not " + str(D["y2"]) diff --git a/tests/test_optional/test_matplotlylib/test_lines.py b/tests/test_optional/test_matplotlylib/test_lines.py index c41dd84..b28f9f6 100644 --- a/tests/test_optional/test_matplotlylib/test_lines.py +++ b/tests/test_optional/test_matplotlylib/test_lines.py @@ -1,5 +1,5 @@ from ...utils import compare_dict, strip_dict_params -from ...test_optional.optional_utils import run_fig +from matplotlylib import mpl_to_plotly from ...test_optional.test_matplotlylib.data.lines import ( COMPLICATED_LINE, D, @@ -12,15 +12,15 @@ def test_simple_line(): fig, ax = plt.subplots() ax.plot(D["x1"], D["y1"], label="simple") - renderer = run_fig(fig) - for data_no, data_dict in enumerate(renderer.plotly_fig["data"]): + plotly_fig = mpl_to_plotly(fig) + for data_no, data_dict in enumerate(plotly_fig["data"]): d1, d2 = strip_dict_params( data_dict, SIMPLE_LINE["data"][data_no], ignore=["uid"] ) equivalent, msg = compare_dict(d1, d2) assert equivalent, msg - equivalent, msg = compare_dict(renderer.plotly_fig["layout"], SIMPLE_LINE["layout"]) + equivalent, msg = compare_dict(plotly_fig["layout"], SIMPLE_LINE["layout"]) assert equivalent, msg @@ -38,8 +38,8 @@ def test_complicated_line(): label="three", ) ax.plot(D["x2"], D["y2"], "--r", linewidth=2, alpha=0.8, label="four") - renderer = run_fig(fig) - for data_no, data_dict in enumerate(renderer.plotly_fig["data"]): + plotly_fig = mpl_to_plotly(fig) + for data_no, data_dict in enumerate(plotly_fig["data"]): d1, d2 = strip_dict_params( data_dict, COMPLICATED_LINE["data"][data_no], ignore=["uid"] ) @@ -47,7 +47,5 @@ def test_complicated_line(): equivalent, msg = compare_dict(d1, d2) assert equivalent, msg - equivalent, msg = compare_dict( - renderer.plotly_fig["layout"], COMPLICATED_LINE["layout"] - ) + equivalent, msg = compare_dict(plotly_fig["layout"], COMPLICATED_LINE["layout"]) assert equivalent, msg diff --git a/tests/test_optional/test_matplotlylib/test_scatter.py b/tests/test_optional/test_matplotlylib/test_scatter.py index 64d4984..b5742e6 100644 --- a/tests/test_optional/test_matplotlylib/test_scatter.py +++ b/tests/test_optional/test_matplotlylib/test_scatter.py @@ -1,5 +1,5 @@ from ...utils import compare_dict, strip_dict_params -from ...test_optional.optional_utils import run_fig +from matplotlylib import mpl_to_plotly from ...test_optional.test_matplotlylib.data.scatter import ( D, DOUBLE_SCATTER, @@ -12,16 +12,14 @@ def test_simple_scatter(): fig, ax = plt.subplots() ax.scatter(D["x1"], D["y1"]) - renderer = run_fig(fig) - for data_no, data_dict in enumerate(renderer.plotly_fig["data"]): + plotly_fig = mpl_to_plotly(fig) + for data_no, data_dict in enumerate(plotly_fig["data"]): d1, d2 = strip_dict_params( data_dict, SIMPLE_SCATTER["data"][data_no], ignore=["uid"] ) assert d1 == d2 - equivalent, msg = compare_dict( - renderer.plotly_fig["layout"], SIMPLE_SCATTER["layout"] - ) + equivalent, msg = compare_dict(plotly_fig["layout"], SIMPLE_SCATTER["layout"]) assert equivalent, msg @@ -29,14 +27,12 @@ def test_double_scatter(): fig, ax = plt.subplots() ax.scatter(D["x1"], D["y1"], color="red", s=121, marker="^", alpha=0.5) ax.scatter(D["x2"], D["y2"], color="purple", s=64, marker="s", alpha=0.5) - renderer = run_fig(fig) - for data_no, data_dict in enumerate(renderer.plotly_fig["data"]): + plotly_fig = mpl_to_plotly(fig) + for data_no, data_dict in enumerate(plotly_fig["data"]): d1, d2 = strip_dict_params( data_dict, DOUBLE_SCATTER["data"][data_no], ignore=["uid"] ) assert d1 == d2 - equivalent, msg = compare_dict( - renderer.plotly_fig["layout"], DOUBLE_SCATTER["layout"] - ) + equivalent, msg = compare_dict(plotly_fig["layout"], DOUBLE_SCATTER["layout"]) assert equivalent, msg diff --git a/tests/test_optional/test_matplotlylib/test_subplots.py b/tests/test_optional/test_matplotlylib/test_subplots.py index bf74b0e..0e819ef 100644 --- a/tests/test_optional/test_matplotlylib/test_subplots.py +++ b/tests/test_optional/test_matplotlylib/test_subplots.py @@ -1,5 +1,5 @@ from ...utils import compare_dict, strip_dict_params -from ...test_optional.optional_utils import run_fig +from matplotlylib import mpl_to_plotly from ...test_optional.test_matplotlylib.data.subplots import D, BLANK_SUBPLOTS from matplotlib.gridspec import GridSpec @@ -19,15 +19,13 @@ def test_blank_subplots(): fig.add_subplot(gs[1:3, 4:]) fig.add_subplot(gs[3, 5]) gs.update(hspace=0.6, wspace=0.6) - renderer = run_fig(fig) + plotly_fig = mpl_to_plotly(fig) - for data_no, data_dict in enumerate(renderer.plotly_fig["data"]): + for data_no, data_dict in enumerate(plotly_fig["data"]): d1, d2 = strip_dict_params( data_dict, BLANK_SUBPLOTS["data"][data_no], ignore=["uid"] ) equivalent, msg = compare_dict(d1, d2) - equivalent, msg = compare_dict( - renderer.plotly_fig["layout"], BLANK_SUBPLOTS["layout"] - ) + equivalent, msg = compare_dict(plotly_fig["layout"], BLANK_SUBPLOTS["layout"]) assert equivalent, msg From 1ff7fe21f0475ea39bcc0e3dba159aaa968ddef2 Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Fri, 4 Dec 2026 01:45:48 +0000 Subject: [PATCH 08/23] Use plain pytest functions in test_date_times Turn the TestDateTimes unittest.TestCase methods into module-level test functions and their self.assertEqual calls into plain asserts, as in the rest of the test suite. --- .../test_matplotlylib/test_date_times.py | 107 +++++++++--------- 1 file changed, 53 insertions(+), 54 deletions(-) diff --git a/tests/test_optional/test_matplotlylib/test_date_times.py b/tests/test_optional/test_matplotlylib/test_date_times.py index fefdfaf..f8d9393 100644 --- a/tests/test_optional/test_matplotlylib/test_date_times.py +++ b/tests/test_optional/test_matplotlylib/test_date_times.py @@ -1,6 +1,5 @@ import datetime import random -from unittest import TestCase import pandas as pd @@ -10,56 +9,56 @@ import matplotlib.pyplot as plt -class TestDateTimes(TestCase): - def test_normal_mpl_dates(self): - datetime_format = "%Y-%m-%d %H:%M:%S" - y = [1, 2, 3, 4] - date_strings = [ - "2010-01-04 00:00:00", - "2010-01-04 10:00:00", - "2010-01-04 23:00:59", - "2010-01-05 00:00:00", - ] - - # 1. create datetimes from the strings - dates = [ - datetime.datetime.strptime(date_string, datetime_format) - for date_string in date_strings - ] - - # 2. create the mpl_dates from these datetimes - mpl_dates = date2num(dates) - - # make a figure in mpl - fig, ax = plt.subplots() - ax.plot_date(mpl_dates, y) - - # convert this figure to plotly's graph_objs - pfig = mpl_to_plotly(fig) - - # we use the same format here, so we expect equality here - self.assertEqual(fig.axes[0].lines[0].get_xydata()[0][0], 7.33776000e05) - self.assertEqual(tuple(pfig["data"][0]["x"]), tuple(date_strings)) - - def test_pandas_time_series_date_formatter(self): - ndays = 3 - x = pd.date_range("1/1/2001", periods=ndays, freq="D") - y = [random.randint(0, 10) for i in range(ndays)] - s = pd.DataFrame(y, columns=["a"]) - - s["Date"] = x - s.plot(x="Date") - - fig = plt.gcf() - pfig = mpl_to_plotly(fig) - - expected_x = ( - "2001-01-01 00:00:00", - "2001-01-02 00:00:00", - "2001-01-03 00:00:00", - ) - expected_x0 = 11323.0 # this is floating point days since epoch - - x0 = fig.axes[0].lines[0].get_xydata()[0][0] - self.assertEqual(x0, expected_x0) - self.assertEqual(pfig["data"][0]["x"], expected_x) +def test_normal_mpl_dates(): + datetime_format = "%Y-%m-%d %H:%M:%S" + y = [1, 2, 3, 4] + date_strings = [ + "2010-01-04 00:00:00", + "2010-01-04 10:00:00", + "2010-01-04 23:00:59", + "2010-01-05 00:00:00", + ] + + # 1. create datetimes from the strings + dates = [ + datetime.datetime.strptime(date_string, datetime_format) + for date_string in date_strings + ] + + # 2. create the mpl_dates from these datetimes + mpl_dates = date2num(dates) + + # make a figure in mpl + fig, ax = plt.subplots() + ax.plot_date(mpl_dates, y) + + # convert this figure to plotly's graph_objs + pfig = mpl_to_plotly(fig) + + # we use the same format here, so we expect equality here + assert fig.axes[0].lines[0].get_xydata()[0][0] == 7.33776000e05 + assert tuple(pfig["data"][0]["x"]) == tuple(date_strings) + + +def test_pandas_time_series_date_formatter(): + ndays = 3 + x = pd.date_range("1/1/2001", periods=ndays, freq="D") + y = [random.randint(0, 10) for i in range(ndays)] + s = pd.DataFrame(y, columns=["a"]) + + s["Date"] = x + s.plot(x="Date") + + fig = plt.gcf() + pfig = mpl_to_plotly(fig) + + expected_x = ( + "2001-01-01 00:00:00", + "2001-01-02 00:00:00", + "2001-01-03 00:00:00", + ) + expected_x0 = 11323.0 # this is floating point days since epoch + + x0 = fig.axes[0].lines[0].get_xydata()[0][0] + assert x0 == expected_x0 + assert pfig["data"][0]["x"] == expected_x From e455eab11aef2ee2a17c63d2ca147c22eebbb730 Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Fri, 4 Dec 2026 01:46:36 +0000 Subject: [PATCH 09/23] Compare numbers with pytest.approx in compare_dict Replace the comp_nums and comp_num_list helpers with pytest.approx, keeping the same absolute tolerance. comp_num_list compared lists with zip, so a list shorter than the expected one passed; pytest.approx also checks that the lengths match. --- tests/utils.py | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/tests/utils.py b/tests/utils.py index d0024f7..6ba836e 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -1,6 +1,8 @@ import copy from numbers import Number as Num +import pytest + def compare_dict(dict1, dict2, equivalent=True, msg="", tol=10e-8): for key in dict1: @@ -13,13 +15,13 @@ def compare_dict(dict1, dict2, equivalent=True, msg="", tol=10e-8): if isinstance(dict1[key], dict): equivalent, msg = compare_dict(dict1[key], dict2[key], tol=tol) elif isinstance(dict1[key], Num) and isinstance(dict2[key], Num): - if not comp_nums(dict1[key], dict2[key], tol): + if dict1[key] != pytest.approx(dict2[key], abs=tol): return ( False, "['{0}'] = {1} should be {2}".format(key, dict1[key], dict2[key]), ) elif is_num_list(dict1[key]) and is_num_list(dict2[key]): - if not comp_num_list(dict1[key], dict2[key], tol): + if dict1[key] != pytest.approx(dict2[key], abs=tol): return ( False, "['{0}'] = {1} should be {2}".format(key, dict1[key], dict2[key]), @@ -63,17 +65,6 @@ def strip_dict_params(d1, d2, ignore=["uid"]): return d1_copy, d2_copy -def comp_nums(num1, num2, tol=10e-8): - return abs(num1 - num2) < tol - - -def comp_num_list(list1, list2, tol=10e-8): - for item1, item2 in zip(list1, list2): - if not comp_nums(item1, item2, tol): - return False - return True - - def is_num_list(item): try: for thing in item: From dbfe0d02f8d4edbe727945603567dca1cb2b1502 Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Fri, 4 Dec 2026 01:56:27 +0000 Subject: [PATCH 10/23] Use fixed y values in the pandas date test The test only checks the x values, but drew its y values from random.randint, so each run plotted different data. Use fixed values instead. --- tests/test_optional/test_matplotlylib/test_date_times.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/test_optional/test_matplotlylib/test_date_times.py b/tests/test_optional/test_matplotlylib/test_date_times.py index f8d9393..5e51d9f 100644 --- a/tests/test_optional/test_matplotlylib/test_date_times.py +++ b/tests/test_optional/test_matplotlylib/test_date_times.py @@ -1,5 +1,4 @@ import datetime -import random import pandas as pd @@ -43,7 +42,7 @@ def test_normal_mpl_dates(): def test_pandas_time_series_date_formatter(): ndays = 3 x = pd.date_range("1/1/2001", periods=ndays, freq="D") - y = [random.randint(0, 10) for i in range(ndays)] + y = list(range(ndays)) s = pd.DataFrame(y, columns=["a"]) s["Date"] = x From 2bc207ac0d2077f229782c2daf2141844b27df24 Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Fri, 4 Dec 2026 02:02:51 +0000 Subject: [PATCH 11/23] Take the figure from the pandas plot in the pandas date test Use the figure of the axes that DataFrame.plot returns instead of plt.gcf(), so the test does not depend on which figure is current. --- tests/test_optional/test_matplotlylib/test_date_times.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/tests/test_optional/test_matplotlylib/test_date_times.py b/tests/test_optional/test_matplotlylib/test_date_times.py index 5e51d9f..ee02fa8 100644 --- a/tests/test_optional/test_matplotlylib/test_date_times.py +++ b/tests/test_optional/test_matplotlylib/test_date_times.py @@ -46,9 +46,7 @@ def test_pandas_time_series_date_formatter(): s = pd.DataFrame(y, columns=["a"]) s["Date"] = x - s.plot(x="Date") - - fig = plt.gcf() + fig = s.plot(x="Date").figure pfig = mpl_to_plotly(fig) expected_x = ( From 0f1511ff862cdf9d0bcfe563b81f50636b58a903 Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Fri, 4 Dec 2026 02:03:46 +0000 Subject: [PATCH 12/23] Close matplotlib figures after each test mpl_to_plotly closes the figure it converts, but a test that fails before calling it leaves its figure open for the rest of the run. Add an autouse fixture that closes all figures after each test in tests/. --- tests/conftest.py | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 tests/conftest.py diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..b758441 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,9 @@ +import matplotlib.pyplot as plt +import pytest + + +@pytest.fixture(autouse=True) +def close_figures(): + """Close all matplotlib figures after each test.""" + yield + plt.close("all") From abd1afb9a982f93cf62ebb6e00e4473fa8427989 Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Fri, 4 Dec 2026 02:19:29 +0000 Subject: [PATCH 13/23] Move the ported tests into tests/ plotly.py kept these tests in tests/test_optional/test_matplotlylib because they need matplotlib, an optional dependency there, and its CI runs tests/test_optional separately with the optional extras installed. Here matplotlib is required and all tests run together, so move the test modules and their expected data next to test_renderer.py and simplify their relative imports. --- tests/{test_optional/test_matplotlylib => }/data/__init__.py | 0 .../{test_optional/test_matplotlylib => }/data/annotations.py | 0 .../{test_optional/test_matplotlylib => }/data/axis_scales.py | 0 tests/{test_optional/test_matplotlylib => }/data/bars.py | 0 tests/{test_optional/test_matplotlylib => }/data/data.py | 0 tests/{test_optional/test_matplotlylib => }/data/lines.py | 0 tests/{test_optional/test_matplotlylib => }/data/scatter.py | 0 tests/{test_optional/test_matplotlylib => }/data/subplots.py | 0 .../{test_optional/test_matplotlylib => }/test_annotations.py | 4 ++-- .../{test_optional/test_matplotlylib => }/test_axis_scales.py | 4 ++-- tests/{test_optional/test_matplotlylib => }/test_bars.py | 4 ++-- tests/{test_optional/test_matplotlylib => }/test_data.py | 2 +- .../{test_optional/test_matplotlylib => }/test_date_times.py | 0 tests/{test_optional/test_matplotlylib => }/test_lines.py | 4 ++-- tests/test_optional/__init__.py | 0 tests/test_optional/test_matplotlylib/__init__.py | 0 tests/{test_optional/test_matplotlylib => }/test_scatter.py | 4 ++-- tests/{test_optional/test_matplotlylib => }/test_subplots.py | 4 ++-- 18 files changed, 13 insertions(+), 13 deletions(-) rename tests/{test_optional/test_matplotlylib => }/data/__init__.py (100%) rename tests/{test_optional/test_matplotlylib => }/data/annotations.py (100%) rename tests/{test_optional/test_matplotlylib => }/data/axis_scales.py (100%) rename tests/{test_optional/test_matplotlylib => }/data/bars.py (100%) rename tests/{test_optional/test_matplotlylib => }/data/data.py (100%) rename tests/{test_optional/test_matplotlylib => }/data/lines.py (100%) rename tests/{test_optional/test_matplotlylib => }/data/scatter.py (100%) rename tests/{test_optional/test_matplotlylib => }/data/subplots.py (100%) rename tests/{test_optional/test_matplotlylib => }/test_annotations.py (90%) rename tests/{test_optional/test_matplotlylib => }/test_axis_scales.py (84%) rename tests/{test_optional/test_matplotlylib => }/test_bars.py (94%) rename tests/{test_optional/test_matplotlylib => }/test_data.py (97%) rename tests/{test_optional/test_matplotlylib => }/test_date_times.py (100%) rename tests/{test_optional/test_matplotlylib => }/test_lines.py (92%) delete mode 100644 tests/test_optional/__init__.py delete mode 100644 tests/test_optional/test_matplotlylib/__init__.py rename tests/{test_optional/test_matplotlylib => }/test_scatter.py (90%) rename tests/{test_optional/test_matplotlylib => }/test_subplots.py (87%) diff --git a/tests/test_optional/test_matplotlylib/data/__init__.py b/tests/data/__init__.py similarity index 100% rename from tests/test_optional/test_matplotlylib/data/__init__.py rename to tests/data/__init__.py diff --git a/tests/test_optional/test_matplotlylib/data/annotations.py b/tests/data/annotations.py similarity index 100% rename from tests/test_optional/test_matplotlylib/data/annotations.py rename to tests/data/annotations.py diff --git a/tests/test_optional/test_matplotlylib/data/axis_scales.py b/tests/data/axis_scales.py similarity index 100% rename from tests/test_optional/test_matplotlylib/data/axis_scales.py rename to tests/data/axis_scales.py diff --git a/tests/test_optional/test_matplotlylib/data/bars.py b/tests/data/bars.py similarity index 100% rename from tests/test_optional/test_matplotlylib/data/bars.py rename to tests/data/bars.py diff --git a/tests/test_optional/test_matplotlylib/data/data.py b/tests/data/data.py similarity index 100% rename from tests/test_optional/test_matplotlylib/data/data.py rename to tests/data/data.py diff --git a/tests/test_optional/test_matplotlylib/data/lines.py b/tests/data/lines.py similarity index 100% rename from tests/test_optional/test_matplotlylib/data/lines.py rename to tests/data/lines.py diff --git a/tests/test_optional/test_matplotlylib/data/scatter.py b/tests/data/scatter.py similarity index 100% rename from tests/test_optional/test_matplotlylib/data/scatter.py rename to tests/data/scatter.py diff --git a/tests/test_optional/test_matplotlylib/data/subplots.py b/tests/data/subplots.py similarity index 100% rename from tests/test_optional/test_matplotlylib/data/subplots.py rename to tests/data/subplots.py diff --git a/tests/test_optional/test_matplotlylib/test_annotations.py b/tests/test_annotations.py similarity index 90% rename from tests/test_optional/test_matplotlylib/test_annotations.py rename to tests/test_annotations.py index 748f81d..723c832 100644 --- a/tests/test_optional/test_matplotlylib/test_annotations.py +++ b/tests/test_annotations.py @@ -1,8 +1,8 @@ import matplotlib.pyplot as plt -from ...utils import compare_dict, strip_dict_params +from .utils import compare_dict, strip_dict_params from matplotlylib import mpl_to_plotly -from ..test_matplotlylib.data.annotations import ANNOTATIONS +from .data.annotations import ANNOTATIONS def test_annotations(): diff --git a/tests/test_optional/test_matplotlylib/test_axis_scales.py b/tests/test_axis_scales.py similarity index 84% rename from tests/test_optional/test_matplotlylib/test_axis_scales.py rename to tests/test_axis_scales.py index 5a78fb2..303049e 100644 --- a/tests/test_optional/test_matplotlylib/test_axis_scales.py +++ b/tests/test_axis_scales.py @@ -1,6 +1,6 @@ -from ...utils import compare_dict, strip_dict_params +from .utils import compare_dict, strip_dict_params from matplotlylib import mpl_to_plotly -from ...test_optional.test_matplotlylib.data.axis_scales import EVEN_LINEAR_SCALE +from .data.axis_scales import EVEN_LINEAR_SCALE import matplotlib.pyplot as plt diff --git a/tests/test_optional/test_matplotlylib/test_bars.py b/tests/test_bars.py similarity index 94% rename from tests/test_optional/test_matplotlylib/test_bars.py rename to tests/test_bars.py index 43311e1..211eeaf 100644 --- a/tests/test_optional/test_matplotlylib/test_bars.py +++ b/tests/test_bars.py @@ -1,6 +1,6 @@ -from ...utils import compare_dict, strip_dict_params +from .utils import compare_dict, strip_dict_params from matplotlylib import mpl_to_plotly -from ...test_optional.test_matplotlylib.data.bars import ( +from .data.bars import ( D, H_AND_V_BARS, HORIZONTAL_BAR, diff --git a/tests/test_optional/test_matplotlylib/test_data.py b/tests/test_data.py similarity index 97% rename from tests/test_optional/test_matplotlylib/test_data.py rename to tests/test_data.py index 2ffa7d7..251b909 100644 --- a/tests/test_optional/test_matplotlylib/test_data.py +++ b/tests/test_data.py @@ -1,5 +1,5 @@ from matplotlylib import mpl_to_plotly -from ...test_optional.test_matplotlylib.data.data import D +from .data.data import D import matplotlib.pyplot as plt diff --git a/tests/test_optional/test_matplotlylib/test_date_times.py b/tests/test_date_times.py similarity index 100% rename from tests/test_optional/test_matplotlylib/test_date_times.py rename to tests/test_date_times.py diff --git a/tests/test_optional/test_matplotlylib/test_lines.py b/tests/test_lines.py similarity index 92% rename from tests/test_optional/test_matplotlylib/test_lines.py rename to tests/test_lines.py index b28f9f6..6a0456e 100644 --- a/tests/test_optional/test_matplotlylib/test_lines.py +++ b/tests/test_lines.py @@ -1,6 +1,6 @@ -from ...utils import compare_dict, strip_dict_params +from .utils import compare_dict, strip_dict_params from matplotlylib import mpl_to_plotly -from ...test_optional.test_matplotlylib.data.lines import ( +from .data.lines import ( COMPLICATED_LINE, D, SIMPLE_LINE, diff --git a/tests/test_optional/__init__.py b/tests/test_optional/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/tests/test_optional/test_matplotlylib/__init__.py b/tests/test_optional/test_matplotlylib/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/tests/test_optional/test_matplotlylib/test_scatter.py b/tests/test_scatter.py similarity index 90% rename from tests/test_optional/test_matplotlylib/test_scatter.py rename to tests/test_scatter.py index b5742e6..d34fb3a 100644 --- a/tests/test_optional/test_matplotlylib/test_scatter.py +++ b/tests/test_scatter.py @@ -1,6 +1,6 @@ -from ...utils import compare_dict, strip_dict_params +from .utils import compare_dict, strip_dict_params from matplotlylib import mpl_to_plotly -from ...test_optional.test_matplotlylib.data.scatter import ( +from .data.scatter import ( D, DOUBLE_SCATTER, SIMPLE_SCATTER, diff --git a/tests/test_optional/test_matplotlylib/test_subplots.py b/tests/test_subplots.py similarity index 87% rename from tests/test_optional/test_matplotlylib/test_subplots.py rename to tests/test_subplots.py index 0e819ef..1cafc0e 100644 --- a/tests/test_optional/test_matplotlylib/test_subplots.py +++ b/tests/test_subplots.py @@ -1,6 +1,6 @@ -from ...utils import compare_dict, strip_dict_params +from .utils import compare_dict, strip_dict_params from matplotlylib import mpl_to_plotly -from ...test_optional.test_matplotlylib.data.subplots import D, BLANK_SUBPLOTS +from .data.subplots import D, BLANK_SUBPLOTS from matplotlib.gridspec import GridSpec import matplotlib.pyplot as plt From 95066e52b2d7c59e06ab28b530b80ab6786b8c05 Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Fri, 4 Dec 2026 02:59:14 +0000 Subject: [PATCH 14/23] Update the ported tests' setup for current matplotlib Five ported tests crashed before converting their figures because they used matplotlib APIs that have changed since 2014: - bar(left=...) and barh(bottom=...): these arguments are now x and y - set_xticks(ticks, True) and set_yticks(ticks, True): the second positional argument used to be minor and is now labels, so pass minor=True - plot_date, removed in matplotlib 3.11: with its default arguments it called xaxis_date() and then plot(x, y, "o"), so do that directly The tests now get as far as comparing the figures with their expected data, which dates from 2014 and is updated in later commits. --- tests/test_axis_scales.py | 4 ++-- tests/test_bars.py | 8 ++++---- tests/test_date_times.py | 3 ++- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/tests/test_axis_scales.py b/tests/test_axis_scales.py index 303049e..5712691 100644 --- a/tests/test_axis_scales.py +++ b/tests/test_axis_scales.py @@ -10,8 +10,8 @@ def test_even_linear_scale(): x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] y = [10, 3, 100, 6, 45, 4, 80, 45, 3, 59] ax.plot(x, y) - ax.set_xticks(list(range(0, 20, 3)), True) - ax.set_yticks(list(range(0, 200, 13)), True) + ax.set_xticks(list(range(0, 20, 3)), minor=True) + ax.set_yticks(list(range(0, 200, 13)), minor=True) plotly_fig = mpl_to_plotly(fig) for data_no, data_dict in enumerate(plotly_fig["data"]): d1, d2 = strip_dict_params( diff --git a/tests/test_bars.py b/tests/test_bars.py index 211eeaf..d635593 100644 --- a/tests/test_bars.py +++ b/tests/test_bars.py @@ -12,7 +12,7 @@ def test_vertical_bar(): fig, ax = plt.subplots() - ax.bar(left=D["left"], height=D["height"]) + ax.bar(x=D["left"], height=D["height"]) plotly_fig = mpl_to_plotly(fig) for data_no, data_dict in enumerate(plotly_fig["data"]): @@ -29,7 +29,7 @@ def test_vertical_bar(): def test_horizontal_bar(): fig, ax = plt.subplots() - ax.barh(bottom=D["bottom"], width=D["width"]) + ax.barh(y=D["bottom"], width=D["width"]) plotly_fig = mpl_to_plotly(fig) for data_no, data_dict in enumerate(plotly_fig["data"]): @@ -47,7 +47,7 @@ def test_horizontal_bar(): def test_h_and_v_bars(): fig, ax = plt.subplots() ax.bar( - left=D["multi_left"], + x=D["multi_left"], height=D["multi_height"], width=10, color="green", @@ -55,7 +55,7 @@ def test_h_and_v_bars(): ) # changing height 10 -> 14 because ValueError if bargap not in [0, 1] ax.barh( - bottom=D["multi_bottom"], + y=D["multi_bottom"], width=D["multi_width"], height=14, color="red", diff --git a/tests/test_date_times.py b/tests/test_date_times.py index ee02fa8..6492f54 100644 --- a/tests/test_date_times.py +++ b/tests/test_date_times.py @@ -29,7 +29,8 @@ def test_normal_mpl_dates(): # make a figure in mpl fig, ax = plt.subplots() - ax.plot_date(mpl_dates, y) + ax.xaxis_date() + ax.plot(mpl_dates, y, "o") # convert this figure to plotly's graph_objs pfig = mpl_to_plotly(fig) From 167e0901bc46e36d1ed4076413ade3fb2e84a501 Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Fri, 4 Dec 2026 02:53:26 +0000 Subject: [PATCH 15/23] Rewrite test_data with direct assertions The tests compared each trace's x and y with the input through zip, so they passed when the output dropped points, and one assertion message reported the wrong trace. Check the number of traces and compare x and y as whole lists instead, including the bar positions that the bar tests did not check. Move the input data into the test module and delete tests/data/data.py. --- tests/data/data.py | 6 ---- tests/test_data.py | 76 +++++++++++++++++++++++----------------------- 2 files changed, 38 insertions(+), 44 deletions(-) delete mode 100644 tests/data/data.py diff --git a/tests/data/data.py b/tests/data/data.py deleted file mode 100644 index 9845f3a..0000000 --- a/tests/data/data.py +++ /dev/null @@ -1,6 +0,0 @@ -D = dict( - x1=[0, 1, 2, 3, 4, 5], - y1=[10, 20, 50, 80, 100, 200], - x2=[0, 1, 2, 3, 4, 5, 6], - y2=[1, 4, 8, 16, 32, 64, 128], -) diff --git a/tests/test_data.py b/tests/test_data.py index 251b909..0b98cf1 100644 --- a/tests/test_data.py +++ b/tests/test_data.py @@ -1,60 +1,60 @@ +import matplotlib.pyplot as plt + from matplotlylib import mpl_to_plotly -from .data.data import D -import matplotlib.pyplot as plt +X1 = [0, 1, 2, 3, 4, 5] +Y1 = [10, 20, 50, 80, 100, 200] +X2 = [0, 1, 2, 3, 4, 5, 6] +Y2 = [1, 4, 8, 16, 32, 64, 128] def test_line_data(): fig, ax = plt.subplots() - ax.plot(D["x1"], D["y1"]) + ax.plot(X1, Y1) + plotly_fig = mpl_to_plotly(fig) - for xi, xf, yi, yf in zip( - plotly_fig["data"][0]["x"], - D["x1"], - plotly_fig["data"][0]["y"], - D["y1"], - ): - assert xi == xf, str(plotly_fig["data"][0]["x"]) + " is not " + str(D["x1"]) - assert yi == yf, str(plotly_fig["data"][0]["y"]) + " is not " + str(D["y1"]) + + assert len(plotly_fig.data) == 1 + assert list(plotly_fig.data[0].x) == X1 + assert list(plotly_fig.data[0].y) == Y1 def test_lines_data(): fig, ax = plt.subplots() - ax.plot(D["x1"], D["y1"]) - ax.plot(D["x2"], D["y2"]) + ax.plot(X1, Y1) + ax.plot(X2, Y2) + plotly_fig = mpl_to_plotly(fig) - for xi, xf, yi, yf in zip( - plotly_fig["data"][0]["x"], - D["x1"], - plotly_fig["data"][0]["y"], - D["y1"], - ): - assert xi == xf, str(plotly_fig["data"][0]["x"]) + " is not " + str(D["x1"]) - assert yi == yf, str(plotly_fig["data"][0]["y"]) + " is not " + str(D["y1"]) - for xi, xf, yi, yf in zip( - plotly_fig["data"][1]["x"], - D["x2"], - plotly_fig["data"][1]["y"], - D["y2"], - ): - assert xi == xf, str(plotly_fig["data"][1]["x"]) + " is not " + str(D["x2"]) - assert yi == yf, str(plotly_fig["data"][0]["y"]) + " is not " + str(D["y2"]) + + assert len(plotly_fig.data) == 2 + assert list(plotly_fig.data[0].x) == X1 + assert list(plotly_fig.data[0].y) == Y1 + assert list(plotly_fig.data[1].x) == X2 + assert list(plotly_fig.data[1].y) == Y2 def test_bar_data(): fig, ax = plt.subplots() - ax.bar(D["x1"], D["y1"]) + ax.bar(X1, Y1) + plotly_fig = mpl_to_plotly(fig) - for yi, yf in zip(plotly_fig["data"][0]["y"], D["y1"]): - assert yi == yf, str(plotly_fig["data"][0]["y"]) + " is not " + str(D["y1"]) + + assert len(plotly_fig.data) == 1 + assert list(plotly_fig.data[0].x) == X1 + assert list(plotly_fig.data[0].y) == Y1 def test_bars_data(): fig, ax = plt.subplots() - ax.bar(D["x1"], D["y1"], color="r") - ax.barh(D["x2"], D["y2"], color="b") + ax.bar(X1, Y1, color="r") + ax.barh(X2, Y2, color="b") + plotly_fig = mpl_to_plotly(fig) - for yi, yf in zip(plotly_fig["data"][0]["y"], D["y1"]): - assert yi == yf, str(plotly_fig["data"][0]["y"]) + " is not " + str(D["y1"]) - for xi, yf in zip(plotly_fig["data"][1]["x"], D["y2"]): - assert xi == yf, str(plotly_fig["data"][1]["x"]) + " is not " + str(D["y2"]) + + assert len(plotly_fig.data) == 2 + # Vertical bars: positions on x, heights on y + assert list(plotly_fig.data[0].x) == X1 + assert list(plotly_fig.data[0].y) == Y1 + # Horizontal bars: widths on x, positions on y + assert list(plotly_fig.data[1].x) == Y2 + assert list(plotly_fig.data[1].y) == X2 From cf416c4cacdb776aa1a73c28b60100670f90effe Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Fri, 4 Dec 2026 03:03:04 +0000 Subject: [PATCH 16/23] Rewrite test_bars with targeted assertions Compare only the bar properties each test is about: orientation, the bar positions and lengths, colour, opacity and bargap. The full-figure snapshots also compared margins, axis ranges and fonts, so they failed on unrelated styling changes. The snapshot for test_h_and_v_bars expected bargap=1, the raw gap in data units. Since 7cfc307 bargap is the gap as a fraction of the bar spacing, so the horizontal bars (14 high at spacing 15) give 1/15. Move the input data into the tests and delete tests/data/bars.py. --- tests/data/bars.py | 174 --------------------------------------------- tests/test_bars.py | 94 ++++++++++++------------ 2 files changed, 50 insertions(+), 218 deletions(-) delete mode 100644 tests/data/bars.py diff --git a/tests/data/bars.py b/tests/data/bars.py deleted file mode 100644 index 7a5f3cb..0000000 --- a/tests/data/bars.py +++ /dev/null @@ -1,174 +0,0 @@ -import plotly.graph_objs as go - -D = dict( - left=[0, 1, 2, 3, 4, 5], - height=[10, 20, 50, 80, 100, 200], - bottom=[0, 1, 2, 3, 4, 5, 6], - width=[1, 4, 8, 16, 32, 64, 128], - multi_left=[0, 10, 20, 30, 40, 50], - multi_height=[1, 4, 8, 16, 32, 64], - multi_bottom=[15, 30, 45, 60, 75, 90], - multi_width=[30, 60, 20, 50, 60, 30], -) - -VERTICAL_BAR = go.Figure( - data=[ - go.Bar( - x=[0.0, 1.0, 2.0, 3.0, 4.0, 5.0], - y=[10.0, 20.0, 50.0, 80.0, 100.0, 200.0], - orientation="v", - marker=go.bar.Marker(line=dict(width=1.0), color="#1F77B4"), - opacity=1, - xaxis="x1", - yaxis="y1", - ) - ], - layout=go.Layout( - width=640, - height=480, - autosize=False, - margin=go.layout.Margin(l=80, r=63, b=52, t=57, pad=0), - hovermode="closest", - showlegend=False, - bargap=0.2, - xaxis1=go.layout.XAxis( - domain=[0.0, 1.0], - range=[-0.68999999999999995, 5.6899999999999995], - type="linear", - showline=True, - ticks="inside", - nticks=8, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="y1", - side="bottom", - mirror="ticks", - ), - yaxis1=go.layout.YAxis( - domain=[0.0, 1.0], - range=[0.0, 210.0], - type="linear", - showline=True, - ticks="inside", - nticks=10, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="x1", - side="left", - mirror="ticks", - ), - ), -) - -HORIZONTAL_BAR = go.Figure( - data=[ - go.Bar( - x=[1.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0], - y=[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], - orientation="h", - marker=go.bar.Marker(line=dict(width=1.0), color="#1F77B4"), - opacity=1, - xaxis="x1", - yaxis="y1", - ) - ], - layout=go.Layout( - width=640, - height=480, - autosize=False, - margin=go.layout.Margin(l=80, r=63, b=52, t=57, pad=0), - hovermode="closest", - showlegend=False, - bargap=0.19999999999999996, - xaxis1=go.layout.XAxis( - domain=[0.0, 1.0], - range=[0.0, 134.40000000000001], - type="linear", - showline=True, - ticks="inside", - nticks=8, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="y1", - side="bottom", - mirror="ticks", - ), - yaxis1=go.layout.YAxis( - domain=[0.0, 1.0], - range=[-0.73999999999999999, 6.7399999999999993], - type="linear", - showline=True, - ticks="inside", - nticks=9, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="x1", - side="left", - mirror="ticks", - ), - ), -) - -H_AND_V_BARS = go.Figure( - data=[ - go.Bar( - x=[0.0, 10.0, 20.0, 30.0, 40.0, 50.0], - y=[1.0, 4.0, 8.0, 16.0, 32.0, 64.0], - orientation="v", - marker=go.bar.Marker(line=dict(width=1.0), color="rgba(0, 128, 0, 0.5)"), - opacity=0.5, - xaxis="x1", - yaxis="y1", - ), - go.Bar( - x=[30.0, 60.0, 20.0, 50.0, 60.0, 30.0], - y=[15.0, 30.0, 45.0, 60.0, 75.0, 90.0], - orientation="h", - marker=go.bar.Marker(line=dict(width=1.0), color="rgba(255, 0, 0, 0.5)"), - opacity=0.5, - xaxis="x1", - yaxis="y1", - ), - ], - layout=go.Layout( - width=640, - height=480, - autosize=False, - margin=go.layout.Margin(l=80, r=63, b=52, t=57, pad=0), - hovermode="closest", - showlegend=False, - bargap=1, - xaxis1=go.layout.XAxis( - domain=[0.0, 1.0], - range=[-8.25, 63.25], - type="linear", - showline=True, - ticks="inside", - nticks=9, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="y1", - side="bottom", - mirror="ticks", - ), - yaxis1=go.layout.YAxis( - domain=[0.0, 1.0], - range=[0.0, 101.84999999999999], - type="linear", - showline=True, - ticks="inside", - nticks=7, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="x1", - side="left", - mirror="ticks", - ), - ), -) diff --git a/tests/test_bars.py b/tests/test_bars.py index d635593..eb67a09 100644 --- a/tests/test_bars.py +++ b/tests/test_bars.py @@ -1,74 +1,80 @@ -from .utils import compare_dict, strip_dict_params -from matplotlylib import mpl_to_plotly -from .data.bars import ( - D, - H_AND_V_BARS, - HORIZONTAL_BAR, - VERTICAL_BAR, -) - import matplotlib.pyplot as plt +import pytest + +from matplotlylib import mpl_to_plotly def test_vertical_bar(): fig, ax = plt.subplots() - ax.bar(x=D["left"], height=D["height"]) - plotly_fig = mpl_to_plotly(fig) - - for data_no, data_dict in enumerate(plotly_fig["data"]): - d1, d2 = strip_dict_params( - data_dict, VERTICAL_BAR["data"][data_no], ignore=["uid"] - ) + ax.bar(x=[0, 1, 2, 3, 4, 5], height=[10, 20, 50, 80, 100, 200]) - equivalent, msg = compare_dict(d1, d2) - assert equivalent, msg + plotly_fig = mpl_to_plotly(fig) - equivalent, msg = compare_dict(plotly_fig["layout"], VERTICAL_BAR["layout"]) - assert equivalent, msg + assert len(plotly_fig.data) == 1 + bar = plotly_fig.data[0] + assert bar.type == "bar" + assert bar.orientation == "v" + assert list(bar.x) == [0, 1, 2, 3, 4, 5] + assert list(bar.y) == [10, 20, 50, 80, 100, 200] + assert bar.marker.color == "#1F77B4" + assert bar.opacity == 1 + # Default bar width 0.8 at spacing 1 + assert plotly_fig.layout.bargap == pytest.approx(0.2) def test_horizontal_bar(): fig, ax = plt.subplots() - ax.barh(y=D["bottom"], width=D["width"]) - plotly_fig = mpl_to_plotly(fig) - - for data_no, data_dict in enumerate(plotly_fig["data"]): - d1, d2 = strip_dict_params( - data_dict, HORIZONTAL_BAR["data"][data_no], ignore=["uid"] - ) + ax.barh(y=[0, 1, 2, 3, 4, 5, 6], width=[1, 4, 8, 16, 32, 64, 128]) - equivalent, msg = compare_dict(d1, d2) - assert equivalent, msg + plotly_fig = mpl_to_plotly(fig) - equivalent, msg = compare_dict(plotly_fig["layout"], HORIZONTAL_BAR["layout"]) - assert equivalent, msg + assert len(plotly_fig.data) == 1 + bar = plotly_fig.data[0] + assert bar.type == "bar" + assert bar.orientation == "h" + assert list(bar.x) == [1, 4, 8, 16, 32, 64, 128] + assert list(bar.y) == [0, 1, 2, 3, 4, 5, 6] + assert bar.marker.color == "#1F77B4" + assert bar.opacity == 1 + # Default bar height 0.8 at spacing 1 + assert plotly_fig.layout.bargap == pytest.approx(0.2) def test_h_and_v_bars(): fig, ax = plt.subplots() ax.bar( - x=D["multi_left"], - height=D["multi_height"], + x=[0, 10, 20, 30, 40, 50], + height=[1, 4, 8, 16, 32, 64], width=10, color="green", alpha=0.5, ) - # changing height 10 -> 14 because ValueError if bargap not in [0, 1] ax.barh( - y=D["multi_bottom"], - width=D["multi_width"], + y=[15, 30, 45, 60, 75, 90], + width=[30, 60, 20, 50, 60, 30], height=14, color="red", alpha=0.5, ) + plotly_fig = mpl_to_plotly(fig) - for data_no, data_dict in enumerate(plotly_fig["data"]): - d1, d2 = strip_dict_params( - data_dict, H_AND_V_BARS["data"][data_no], ignore=["uid"] - ) - equivalent, msg = compare_dict(d1, d2) - assert equivalent, msg + assert len(plotly_fig.data) == 2 + vertical, horizontal = plotly_fig.data + assert vertical.type == "bar" + assert vertical.orientation == "v" + assert list(vertical.x) == [0, 10, 20, 30, 40, 50] + assert list(vertical.y) == [1, 4, 8, 16, 32, 64] + assert vertical.marker.color == "rgba(0, 128, 0, 0.5)" + assert vertical.opacity == 0.5 + + assert horizontal.type == "bar" + assert horizontal.orientation == "h" + assert list(horizontal.x) == [30, 60, 20, 50, 60, 30] + assert list(horizontal.y) == [15, 30, 45, 60, 75, 90] + assert horizontal.marker.color == "rgba(255, 0, 0, 0.5)" + assert horizontal.opacity == 0.5 - equivalent, msg = compare_dict(plotly_fig["layout"], H_AND_V_BARS["layout"]) - assert equivalent, msg + # Plotly has one bargap per figure, and the bars drawn last set it: the + # horizontal bars are 14 high at spacing 15, a gap of 1/15 + assert plotly_fig.layout.bargap == pytest.approx(1 / 15) From e7a6d5d4553ff4c5cb6dd75912088fdd1a7b9f30 Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Fri, 4 Dec 2026 03:10:04 +0000 Subject: [PATCH 17/23] Rewrite test_scatter with targeted assertions Compare only the marker properties each test is about: mode, the points, marker symbol, size and colour. The full-figure snapshots also compared the layout, so they failed on unrelated styling changes. All of these properties still match the 2014 snapshots. Move the input data into the tests and delete tests/data/scatter.py. --- tests/data/scatter.py | 130 ------------------------------------------ tests/test_scatter.py | 62 ++++++++++++-------- 2 files changed, 37 insertions(+), 155 deletions(-) delete mode 100644 tests/data/scatter.py diff --git a/tests/data/scatter.py b/tests/data/scatter.py deleted file mode 100644 index 2417e0a..0000000 --- a/tests/data/scatter.py +++ /dev/null @@ -1,130 +0,0 @@ -import plotly.graph_objs as go - -D = dict( - x1=[1, 2, 2, 4, 5, 6, 1, 7, 8, 5, 3], - y1=[5, 3, 7, 2, 9, 7, 8, 4, 5, 9, 2], - x2=[-1, 1, -0.3, -0.6, 0.4, 0.8, -0.1, 0.7], - y2=[-0.5, 0.4, 0.7, -0.6, 0.3, -1, 0, 0.3], -) - - -SIMPLE_SCATTER = go.Figure( - data=[ - go.Scatter( - x=[1.0, 2.0, 2.0, 4.0, 5.0, 6.0, 1.0, 7.0, 8.0, 5.0, 3.0], - y=[5.0, 3.0, 7.0, 2.0, 9.0, 7.0, 8.0, 4.0, 5.0, 9.0, 2.0], - mode="markers", - marker=go.scatter.Marker( - symbol="circle", - line=dict(color="rgba(31,119,180,1.0)", width=1.0), - size=6.0, - color="rgba(31,119,180,1.0)", - ), - xaxis="x1", - yaxis="y1", - ) - ], - layout=go.Layout( - width=640, - height=480, - autosize=False, - margin=go.layout.Margin(l=80, r=63, b=52, t=57, pad=0), - hovermode="closest", - showlegend=False, - xaxis1=go.layout.XAxis( - domain=[0.0, 1.0], - range=[0.64334677419354847, 8.3566532258064505], - type="linear", - showline=True, - ticks="inside", - nticks=10, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="y1", - side="bottom", - mirror="ticks", - ), - yaxis1=go.layout.YAxis( - domain=[0.0, 1.0], - range=[1.6410714285714287, 9.3589285714285726], - type="linear", - showline=True, - ticks="inside", - nticks=10, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="x1", - side="left", - mirror="ticks", - ), - ), -) - -DOUBLE_SCATTER = go.Figure( - data=[ - go.Scatter( - x=[1.0, 2.0, 2.0, 4.0, 5.0, 6.0, 1.0, 7.0, 8.0, 5.0, 3.0], - y=[5.0, 3.0, 7.0, 2.0, 9.0, 7.0, 8.0, 4.0, 5.0, 9.0, 2.0], - mode="markers", - marker=go.scatter.Marker( - symbol="triangle-up", - line=dict(color="rgba(255,0,0,0.5)", width=1.0), - size=11.0, - color="rgba(255,0,0,0.5)", - ), - xaxis="x1", - yaxis="y1", - ), - go.Scatter( - x=[-1.0, 1.0, -0.3, -0.6, 0.4, 0.8, -0.1, 0.7], - y=[-0.5, 0.4, 0.7, -0.6, 0.3, -1.0, 0.0, 0.3], - mode="markers", - marker=go.scatter.Marker( - symbol="square", - line=dict(color="rgba(128,0,128,0.5)", width=1.0), - size=8.0, - color="rgba(128,0,128,0.5)", - ), - xaxis="x1", - yaxis="y1", - ), - ], - layout=go.Layout( - width=640, - height=480, - autosize=False, - margin=go.layout.Margin(l=80, r=63, b=52, t=57, pad=0), - hovermode="closest", - showlegend=False, - xaxis1=go.layout.XAxis( - domain=[0.0, 1.0], - range=[-1.5159626203173777, 8.4647578206295506], - type="linear", - showline=True, - ticks="inside", - nticks=7, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="y1", - side="bottom", - mirror="ticks", - ), - yaxis1=go.layout.YAxis( - domain=[0.0, 1.0], - range=[-1.588616071428572, 9.5198093820861693], - type="linear", - showline=True, - ticks="inside", - nticks=7, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="x1", - side="left", - mirror="ticks", - ), - ), -) diff --git a/tests/test_scatter.py b/tests/test_scatter.py index d34fb3a..657e821 100644 --- a/tests/test_scatter.py +++ b/tests/test_scatter.py @@ -1,38 +1,50 @@ -from .utils import compare_dict, strip_dict_params +import matplotlib.pyplot as plt + from matplotlylib import mpl_to_plotly -from .data.scatter import ( - D, - DOUBLE_SCATTER, - SIMPLE_SCATTER, -) -import matplotlib.pyplot as plt +X1 = [1, 2, 2, 4, 5, 6, 1, 7, 8, 5, 3] +Y1 = [5, 3, 7, 2, 9, 7, 8, 4, 5, 9, 2] +X2 = [-1, 1, -0.3, -0.6, 0.4, 0.8, -0.1, 0.7] +Y2 = [-0.5, 0.4, 0.7, -0.6, 0.3, -1, 0, 0.3] def test_simple_scatter(): fig, ax = plt.subplots() - ax.scatter(D["x1"], D["y1"]) + ax.scatter(X1, Y1) + plotly_fig = mpl_to_plotly(fig) - for data_no, data_dict in enumerate(plotly_fig["data"]): - d1, d2 = strip_dict_params( - data_dict, SIMPLE_SCATTER["data"][data_no], ignore=["uid"] - ) - assert d1 == d2 - equivalent, msg = compare_dict(plotly_fig["layout"], SIMPLE_SCATTER["layout"]) - assert equivalent, msg + assert len(plotly_fig.data) == 1 + trace = plotly_fig.data[0] + assert trace.type == "scatter" + assert trace.mode == "markers" + assert list(trace.x) == X1 + assert list(trace.y) == Y1 + assert trace.marker.symbol == "circle" + # matplotlib's s is the marker area in points^2, 36 by default + assert trace.marker.size == 6 + assert trace.marker.color == "rgba(31,119,180,1.0)" def test_double_scatter(): fig, ax = plt.subplots() - ax.scatter(D["x1"], D["y1"], color="red", s=121, marker="^", alpha=0.5) - ax.scatter(D["x2"], D["y2"], color="purple", s=64, marker="s", alpha=0.5) + ax.scatter(X1, Y1, color="red", s=121, marker="^", alpha=0.5) + ax.scatter(X2, Y2, color="purple", s=64, marker="s", alpha=0.5) + plotly_fig = mpl_to_plotly(fig) - for data_no, data_dict in enumerate(plotly_fig["data"]): - d1, d2 = strip_dict_params( - data_dict, DOUBLE_SCATTER["data"][data_no], ignore=["uid"] - ) - assert d1 == d2 - - equivalent, msg = compare_dict(plotly_fig["layout"], DOUBLE_SCATTER["layout"]) - assert equivalent, msg + + assert len(plotly_fig.data) == 2 + triangles, squares = plotly_fig.data + assert triangles.mode == "markers" + assert list(triangles.x) == X1 + assert list(triangles.y) == Y1 + assert triangles.marker.symbol == "triangle-up" + assert triangles.marker.size == 11 + assert triangles.marker.color == "rgba(255,0,0,0.5)" + + assert squares.mode == "markers" + assert list(squares.x) == X2 + assert list(squares.y) == Y2 + assert squares.marker.symbol == "square" + assert squares.marker.size == 8 + assert squares.marker.color == "rgba(128,0,128,0.5)" From 3ef71a79cd959d6bad89619224f5b23c0affc4c2 Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Fri, 4 Dec 2026 03:15:45 +0000 Subject: [PATCH 18/23] Rewrite test_lines with targeted assertions Compare only the properties each test is about: mode, name, the points, and the line colour, dash and width or the marker symbol, size, colour and opacity. The full-figure snapshots also compared the layout, so they failed on unrelated styling changes. The snapshots wrote line colours as "rgba (r, g, b, a)". Since efb8905 the converter writes them without the space, so the tests expect that. Move the input data into the tests and delete tests/data/lines.py. --- tests/data/lines.py | 149 -------------------------------------------- tests/test_lines.py | 95 +++++++++++++++++----------- 2 files changed, 59 insertions(+), 185 deletions(-) delete mode 100644 tests/data/lines.py diff --git a/tests/data/lines.py b/tests/data/lines.py deleted file mode 100644 index 0731227..0000000 --- a/tests/data/lines.py +++ /dev/null @@ -1,149 +0,0 @@ -import plotly.graph_objs as go - -D = dict( - x1=[0, 1, 2, 3, 4, 5], - y1=[10, 20, 50, 80, 100, 200], - x2=[0, 1, 2, 3, 4, 5, 6], - y2=[1, 4, 8, 16, 32, 64, 128], -) - -SIMPLE_LINE = go.Figure( - data=[ - go.Scatter( - x=[0.0, 1.0, 2.0, 3.0, 4.0, 5.0], - y=[10.0, 20.0, 50.0, 80.0, 100.0, 200.0], - name="simple", - mode="lines", - line=go.scatter.Line( - dash="solid", color="rgba (31, 119, 180, 1)", width=1.5 - ), - xaxis="x1", - yaxis="y1", - ) - ], - layout=go.Layout( - width=640, - height=480, - autosize=False, - margin=go.layout.Margin(l=80, r=63, b=52, t=57, pad=0), - hovermode="closest", - showlegend=False, - xaxis1=go.layout.XAxis( - domain=[0.0, 1.0], - range=[-0.25, 5.25], - type="linear", - showline=True, - ticks="inside", - nticks=8, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="y1", - side="bottom", - mirror="ticks", - ), - yaxis1=go.layout.YAxis( - domain=[0.0, 1.0], - range=[0.5, 209.5], - type="linear", - showline=True, - ticks="inside", - nticks=10, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="x1", - side="left", - mirror="ticks", - ), - ), -) - -COMPLICATED_LINE = go.Figure( - data=[ - go.Scatter( - x=[0.0, 1.0, 2.0, 3.0, 4.0, 5.0], - y=[10.0, 20.0, 50.0, 80.0, 100.0, 200.0], - name="one", - mode="markers", - marker=go.scatter.Marker( - symbol="circle", - line=dict(color="#FF0000", width=1.0), - size=10, - color="#FF0000", - opacity=0.5, - ), - xaxis="x1", - yaxis="y1", - ), - go.Scatter( - x=[0.0, 1.0, 2.0, 3.0, 4.0, 5.0], - y=[10.0, 20.0, 50.0, 80.0, 100.0, 200.0], - name="two", - mode="lines", - line=dict(dash="solid", color="rgba (0, 0, 255, 0.7)", width=2), - xaxis="x1", - yaxis="y1", - ), - go.Scatter( - x=[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], - y=[1.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0], - name="three", - mode="markers", - marker=go.scatter.Marker( - symbol="cross", - line=dict(color="#0000FF", width=2), - size=10, - color="#0000FF", - opacity=0.6, - ), - xaxis="x1", - yaxis="y1", - ), - go.Scatter( - x=[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], - y=[1.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0], - name="four", - mode="lines", - line=go.scatter.Line(dash="dash", color="rgba (255, 0, 0, 0.8)", width=2), - xaxis="x1", - yaxis="y1", - ), - ], - layout=go.Layout( - width=640, - height=480, - autosize=False, - margin=go.layout.Margin(l=80, r=63, b=52, t=57, pad=0), - hovermode="closest", - showlegend=False, - xaxis1=go.layout.XAxis( - domain=[0.0, 1.0], - range=[-0.30000000000000004, 6.2999999999999998], - type="linear", - showline=True, - ticks="inside", - nticks=9, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="y1", - side="bottom", - mirror="ticks", - ), - yaxis1=go.layout.YAxis( - domain=[0.0, 1.0], - range=[-8.9500000000000011, 209.94999999999999], - type="linear", - showline=True, - ticks="inside", - nticks=11, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="x1", - side="left", - mirror="ticks", - ), - ), -) diff --git a/tests/test_lines.py b/tests/test_lines.py index 6a0456e..e81f384 100644 --- a/tests/test_lines.py +++ b/tests/test_lines.py @@ -1,51 +1,74 @@ -from .utils import compare_dict, strip_dict_params +import matplotlib.pyplot as plt + from matplotlylib import mpl_to_plotly -from .data.lines import ( - COMPLICATED_LINE, - D, - SIMPLE_LINE, -) -import matplotlib.pyplot as plt +X1 = [0, 1, 2, 3, 4, 5] +Y1 = [10, 20, 50, 80, 100, 200] +X2 = [0, 1, 2, 3, 4, 5, 6] +Y2 = [1, 4, 8, 16, 32, 64, 128] def test_simple_line(): fig, ax = plt.subplots() - ax.plot(D["x1"], D["y1"], label="simple") + ax.plot(X1, Y1, label="simple") + plotly_fig = mpl_to_plotly(fig) - for data_no, data_dict in enumerate(plotly_fig["data"]): - d1, d2 = strip_dict_params( - data_dict, SIMPLE_LINE["data"][data_no], ignore=["uid"] - ) - equivalent, msg = compare_dict(d1, d2) - assert equivalent, msg - equivalent, msg = compare_dict(plotly_fig["layout"], SIMPLE_LINE["layout"]) - assert equivalent, msg + assert len(plotly_fig.data) == 1 + trace = plotly_fig.data[0] + assert trace.type == "scatter" + assert trace.mode == "lines" + assert trace.name == "simple" + assert list(trace.x) == X1 + assert list(trace.y) == Y1 + assert trace.line.color == "rgba(31, 119, 180, 1)" + assert trace.line.dash == "solid" + assert trace.line.width == 1.5 def test_complicated_line(): fig, ax = plt.subplots() - ax.plot(D["x1"], D["y1"], "ro", markersize=10, alpha=0.5, label="one") - ax.plot(D["x1"], D["y1"], "-b", linewidth=2, alpha=0.7, label="two") - ax.plot( - D["x2"], - D["y2"], - "b+", - markeredgewidth=2, - markersize=10, - alpha=0.6, - label="three", - ) - ax.plot(D["x2"], D["y2"], "--r", linewidth=2, alpha=0.8, label="four") + ax.plot(X1, Y1, "ro", markersize=10, alpha=0.5, label="one") + ax.plot(X1, Y1, "-b", linewidth=2, alpha=0.7, label="two") + ax.plot(X2, Y2, "b+", markeredgewidth=2, markersize=10, alpha=0.6, label="three") + ax.plot(X2, Y2, "--r", linewidth=2, alpha=0.8, label="four") + plotly_fig = mpl_to_plotly(fig) - for data_no, data_dict in enumerate(plotly_fig["data"]): - d1, d2 = strip_dict_params( - data_dict, COMPLICATED_LINE["data"][data_no], ignore=["uid"] - ) - equivalent, msg = compare_dict(d1, d2) - assert equivalent, msg + assert len(plotly_fig.data) == 4 + red_circles, blue_line, blue_crosses, red_dashes = plotly_fig.data + + assert red_circles.mode == "markers" + assert red_circles.name == "one" + assert list(red_circles.x) == X1 + assert list(red_circles.y) == Y1 + assert red_circles.marker.symbol == "circle" + assert red_circles.marker.size == 10 + assert red_circles.marker.color == "#FF0000" + assert red_circles.marker.opacity == 0.5 + + assert blue_line.mode == "lines" + assert blue_line.name == "two" + assert list(blue_line.x) == X1 + assert list(blue_line.y) == Y1 + assert blue_line.line.color == "rgba(0, 0, 255, 0.7)" + assert blue_line.line.dash == "solid" + assert blue_line.line.width == 2 + + assert blue_crosses.mode == "markers" + assert blue_crosses.name == "three" + assert list(blue_crosses.x) == X2 + assert list(blue_crosses.y) == Y2 + assert blue_crosses.marker.symbol == "cross" + assert blue_crosses.marker.size == 10 + assert blue_crosses.marker.color == "#0000FF" + assert blue_crosses.marker.opacity == 0.6 + assert blue_crosses.marker.line.width == 2 - equivalent, msg = compare_dict(plotly_fig["layout"], COMPLICATED_LINE["layout"]) - assert equivalent, msg + assert red_dashes.mode == "lines" + assert red_dashes.name == "four" + assert list(red_dashes.x) == X2 + assert list(red_dashes.y) == Y2 + assert red_dashes.line.color == "rgba(255, 0, 0, 0.8)" + assert red_dashes.line.dash == "dash" + assert red_dashes.line.width == 2 From a10d439e94dc77e66565f8e9b3a85f570ea239a7 Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Fri, 4 Dec 2026 03:21:46 +0000 Subject: [PATCH 19/23] Rewrite test_annotations with targeted assertions Check that each of the four corner texts becomes an annotation in paper coordinates, with the expected anchors and alignment and a position within 0.005 of the input. The full-figure snapshot also compared the plotted lines and the layout, so it failed on unrelated changes, and compared positions to 12 digits. The annotations still match the 2014 snapshot. Delete tests/data/annotations.py. --- tests/data/annotations.py | 106 -------------------------------------- tests/test_annotations.py | 40 ++++++++++---- 2 files changed, 29 insertions(+), 117 deletions(-) delete mode 100644 tests/data/annotations.py diff --git a/tests/data/annotations.py b/tests/data/annotations.py deleted file mode 100644 index 7ef3f2c..0000000 --- a/tests/data/annotations.py +++ /dev/null @@ -1,106 +0,0 @@ -import plotly.graph_objs as go - -ANNOTATIONS = go.Figure( - data=[ - go.Scatter( - x=[0.0, 1.0, 2.0], - y=[1.0, 2.0, 3.0], - name="_line0", - mode="lines", - line=go.scatter.Line(dash="solid", color="rgba (0, 0, 255, 1)", width=1.5), - xaxis="x1", - yaxis="y1", - ), - go.Scatter( - x=[0.0, 1.0, 2.0], - y=[3.0, 2.0, 1.0], - name="_line1", - mode="lines", - line=go.scatter.Line(dash="solid", color="rgba (0, 0, 255, 1)", width=1.5), - xaxis="x1", - yaxis="y1", - ), - ], - layout=go.Layout( - width=640, - height=480, - autosize=False, - margin=go.layout.Margin(l=80, r=63, b=47, t=47, pad=0), - hovermode="closest", - showlegend=False, - annotations=[ - go.layout.Annotation( - x=0.000997987927565, - y=0.9973865229110511, - text="top-left", - xref="paper", - yref="paper", - showarrow=False, - align="left", - font=dict(size=10.0, color="#000000"), - opacity=1, - xanchor="left", - yanchor="top", - ), - go.layout.Annotation( - x=0.000997987927565, - y=0.0031525606469002573, - text="bottom-left", - xref="paper", - yref="paper", - align="left", - showarrow=False, - font=dict(size=10.0, color="#000000"), - opacity=1, - xanchor="left", - yanchor="bottom", - ), - go.layout.Annotation( - x=0.996989939638, - y=0.9973865229110511, - text="top-right", - xref="paper", - yref="paper", - align="right", - showarrow=False, - font=dict(size=10.0, color="#000000"), - opacity=1, - xanchor="right", - yanchor="top", - ), - go.layout.Annotation( - x=0.996989939638, - y=0.0031525606469002573, - text="bottom-right", - xref="paper", - yref="paper", - align="right", - showarrow=False, - font=dict(size=10.0, color="#000000"), - opacity=1, - xanchor="right", - yanchor="bottom", - ), - ], - xaxis1=go.layout.XAxis( - domain=[0.0, 1.0], - range=(0.0, 2.0), - showline=True, - ticks="inside", - showgrid=False, - zeroline=False, - anchor="y1", - mirror=True, - ), - yaxis1=go.layout.YAxis( - domain=[0.0, 1.0], - range=(1.0, 3.0), - showline=True, - ticks="inside", - showgrid=False, - zeroline=False, - anchor="x1", - mirror=True, - ), - ), -) diff --git a/tests/test_annotations.py b/tests/test_annotations.py index 723c832..117fa42 100644 --- a/tests/test_annotations.py +++ b/tests/test_annotations.py @@ -1,8 +1,7 @@ import matplotlib.pyplot as plt +import pytest -from .utils import compare_dict, strip_dict_params from matplotlylib import mpl_to_plotly -from .data.annotations import ANNOTATIONS def test_annotations(): @@ -17,13 +16,32 @@ def test_annotations(): ax.text( 0.999, 0.001, "bottom-right", transform=ax.transAxes, va="baseline", ha="right" ) + plotly_fig = mpl_to_plotly(fig) - for data_no, data_dict in enumerate(plotly_fig["data"]): - d1, d2 = strip_dict_params( - data_dict, ANNOTATIONS["data"][data_no], ignore=["uid"] - ) - equivalent, msg = compare_dict(d1, d2) - assert equivalent, msg - for no, note in enumerate(plotly_fig["layout"]["annotations"]): - equivalent, msg = compare_dict(note, ANNOTATIONS["layout"]["annotations"][no]) - assert equivalent, msg + + annotations = {a.text: a for a in plotly_fig.layout.annotations} + assert sorted(annotations) == [ + "bottom-left", + "bottom-right", + "top-left", + "top-right", + ] + expected = { + "top-left": (0.001, 0.999, "left", "top"), + "bottom-left": (0.001, 0.001, "left", "bottom"), + "top-right": (0.999, 0.999, "right", "top"), + "bottom-right": (0.999, 0.001, "right", "bottom"), + } + for text, (x, y, xanchor, yanchor) in expected.items(): + annotation = annotations[text] + assert annotation.xref == "paper" + assert annotation.yref == "paper" + assert annotation.showarrow is False + assert annotation.xanchor == xanchor + assert annotation.yanchor == yanchor + assert annotation.align == xanchor + # The plotly plot area is not exactly the size of the matplotlib axes + # (497 vs 496 pixels wide here), so paper coordinates can be off by a + # pixel or two + assert annotation.x == pytest.approx(x, abs=0.005) + assert annotation.y == pytest.approx(y, abs=0.005) From fe8fd9d4eb2cb80d6d52c3695b6800208921e946 Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Fri, 4 Dec 2026 03:25:09 +0000 Subject: [PATCH 20/23] Rewrite test_axis_scales with targeted assertions Check the axis properties the test is about: both axes are linear, their ranges follow the view limits that the minor ticks widen, and, since matplotlib places the major ticks automatically, plotly gets their number rather than explicit tick values or a tick spacing. The full-figure snapshot also compared the plotted line and the rest of the layout, so it failed on unrelated changes. The axes still match the 2014 snapshot. Delete tests/data/axis_scales.py. --- tests/data/axis_scales.py | 56 --------------------------------------- tests/test_axis_scales.py | 36 ++++++++++++++----------- 2 files changed, 20 insertions(+), 72 deletions(-) delete mode 100644 tests/data/axis_scales.py diff --git a/tests/data/axis_scales.py b/tests/data/axis_scales.py deleted file mode 100644 index ba8838d..0000000 --- a/tests/data/axis_scales.py +++ /dev/null @@ -1,56 +0,0 @@ -import plotly.graph_objs as go - -D = dict(x=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], y=[10, 3, 100, 6, 45, 4, 80, 45, 3, 59]) - - -EVEN_LINEAR_SCALE = go.Figure( - data=[ - go.Scatter( - x=[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0], - y=[10.0, 3.0, 100.0, 6.0, 45.0, 4.0, 80.0, 45.0, 3.0, 59.0], - name="_line0", - mode="lines", - line=go.scatter.Line( - dash="solid", color="rgba (31, 119, 180, 1)", width=1.5 - ), - xaxis="x1", - yaxis="y1", - ) - ], - layout=go.Layout( - width=640, - height=480, - autosize=False, - margin=go.layout.Margin(l=80, r=63, b=52, t=57, pad=0), - hovermode="closest", - showlegend=False, - xaxis1=go.layout.XAxis( - domain=[0.0, 1.0], - range=[0.0, 18.0], - type="linear", - showline=True, - nticks=10, - ticks="inside", - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="y1", - side="bottom", - mirror="ticks", - ), - yaxis1=go.layout.YAxis( - domain=[0.0, 1.0], - range=[-1.8500000000000005, 195.0], - type="linear", - showline=True, - nticks=10, - ticks="inside", - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="x1", - side="left", - mirror="ticks", - ), - ), -) diff --git a/tests/test_axis_scales.py b/tests/test_axis_scales.py index 5712691..ed69d95 100644 --- a/tests/test_axis_scales.py +++ b/tests/test_axis_scales.py @@ -1,25 +1,29 @@ -from .utils import compare_dict, strip_dict_params -from matplotlylib import mpl_to_plotly -from .data.axis_scales import EVEN_LINEAR_SCALE - import matplotlib.pyplot as plt +import pytest + +from matplotlylib import mpl_to_plotly def test_even_linear_scale(): fig, ax = plt.subplots() - x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - y = [10, 3, 100, 6, 45, 4, 80, 45, 3, 59] - ax.plot(x, y) + ax.plot([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [10, 3, 100, 6, 45, 4, 80, 45, 3, 59]) + # Minor ticks beyond the data widen the view limits ax.set_xticks(list(range(0, 20, 3)), minor=True) ax.set_yticks(list(range(0, 200, 13)), minor=True) - plotly_fig = mpl_to_plotly(fig) - for data_no, data_dict in enumerate(plotly_fig["data"]): - d1, d2 = strip_dict_params( - data_dict, EVEN_LINEAR_SCALE["data"][data_no], ignore=["uid"] - ) - equivalent, msg = compare_dict(d1, d2) - assert equivalent, msg + plotly_fig = mpl_to_plotly(fig) - equivalent, msg = compare_dict(plotly_fig["layout"], EVEN_LINEAR_SCALE["layout"]) - assert equivalent, msg + xaxis, yaxis = plotly_fig.layout.xaxis, plotly_fig.layout.yaxis + assert xaxis.type == "linear" + assert yaxis.type == "linear" + assert list(xaxis.range) == pytest.approx([0, 18]) + assert list(yaxis.range) == pytest.approx([-1.85, 195]) + # The major ticks come from matplotlib's automatic locator, so plotly gets + # their number (10 on each axis over the widened limits) rather than + # explicit tick values + assert xaxis.nticks == 10 + assert yaxis.nticks == 10 + assert xaxis.tickvals is None + assert yaxis.tickvals is None + assert xaxis.dtick is None + assert yaxis.dtick is None From 30f5f84ae192f64d6aeeb0b17d2d83f64011fea2 Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Fri, 4 Dec 2026 03:30:40 +0000 Subject: [PATCH 21/23] Rewrite test_subplots with targeted assertions Check that each of the eight GridSpec subplots becomes a pair of plotly axes whose domains match its cells and which anchor each other, and that the one line is drawn on the first subplot. The domains are worked out from the GridSpec geometry instead of copied as 12-digit numbers. The full-figure snapshot also compared each axis's styling, so it failed on unrelated changes, and it never asserted on the result of comparing the traces. The domains and anchors still match the 2014 snapshot. Delete tests/data/subplots.py and tests/data/__init__.py, since nothing uses the tests/data package any more. --- tests/data/__init__.py | 1 - tests/data/subplots.py | 249 ----------------------------------------- tests/test_subplots.py | 65 +++++++++-- 3 files changed, 53 insertions(+), 262 deletions(-) delete mode 100644 tests/data/__init__.py delete mode 100644 tests/data/subplots.py diff --git a/tests/data/__init__.py b/tests/data/__init__.py deleted file mode 100644 index 8b13789..0000000 --- a/tests/data/__init__.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/data/subplots.py b/tests/data/subplots.py deleted file mode 100644 index 443ac10..0000000 --- a/tests/data/subplots.py +++ /dev/null @@ -1,249 +0,0 @@ -import plotly.graph_objs as go - -D = dict(x1=[0, 1], y1=[1, 2]) - -BLANK_SUBPLOTS = go.Figure( - data=[ - go.Scatter( - x=[0.0, 1.0], - y=[1.0, 2.0], - name="_line0", - mode="lines", - line=go.scatter.Line(dash="solid", color="#0000FF", width=1.0), - xaxis="x1", - yaxis="y1", - ) - ], - layout=go.Layout( - width=640, - height=480, - autosize=False, - margin=go.layout.Margin(l=168, r=63, b=52, t=57, pad=0), - hovermode="closest", - showlegend=False, - xaxis1=go.layout.XAxis( - domain=[0.0, 0.13513513513513517], - range=[-0.050000000000000003, 1.05], - type="linear", - showline=True, - ticks="inside", - nticks=4, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="y1", - side="bottom", - mirror="ticks", - ), - xaxis2=go.layout.XAxis( - domain=[0.0, 0.13513513513513517], - range=[0.0, 1.0], - type="linear", - showline=True, - ticks="inside", - nticks=2, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="y2", - side="bottom", - mirror="ticks", - ), - xaxis3=go.layout.XAxis( - domain=[0.0, 0.13513513513513517], - range=[0.0, 1.0], - type="linear", - showline=True, - ticks="inside", - nticks=2, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="y3", - side="bottom", - mirror="ticks", - ), - xaxis4=go.layout.XAxis( - domain=[0.2162162162162162, 1.0], - range=[0.0, 1.0], - type="linear", - showline=True, - ticks="inside", - nticks=6, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="y4", - side="bottom", - mirror="ticks", - ), - xaxis5=go.layout.XAxis( - domain=[0.2162162162162162, 0.56756756756756754], - range=[0.0, 1.0], - type="linear", - showline=True, - ticks="inside", - nticks=3, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="y5", - side="bottom", - mirror="ticks", - ), - xaxis6=go.layout.XAxis( - domain=[0.2162162162162162, 0.78378378378378377], - range=[0.0, 1.0], - type="linear", - showline=True, - ticks="inside", - nticks=6, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="y6", - side="bottom", - mirror="ticks", - ), - xaxis7=go.layout.XAxis( - domain=[0.64864864864864857, 1.0], - range=[0.0, 1.0], - type="linear", - showline=True, - ticks="inside", - nticks=3, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="y7", - side="bottom", - mirror="ticks", - ), - xaxis8=go.layout.XAxis( - domain=[0.8648648648648648, 1.0], - range=[0.0, 1.0], - type="linear", - showline=True, - ticks="inside", - nticks=2, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="y8", - side="bottom", - mirror="ticks", - ), - yaxis1=go.layout.YAxis( - domain=[0.82758620689655171, 1.0], - range=[0.94999999999999996, 2.0499999999999998], - type="linear", - showline=True, - ticks="inside", - nticks=4, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="x1", - side="left", - mirror="ticks", - ), - yaxis2=go.layout.YAxis( - domain=[0.55172413793103448, 0.72413793103448265], - range=[0.0, 1.0], - type="linear", - showline=True, - ticks="inside", - nticks=3, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="x2", - side="left", - mirror="ticks", - ), - yaxis3=go.layout.YAxis( - domain=[0.0, 0.44827586206896547], - range=[0.0, 1.0], - type="linear", - showline=True, - ticks="inside", - nticks=6, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="x3", - side="left", - mirror="ticks", - ), - yaxis4=go.layout.YAxis( - domain=[0.82758620689655171, 1.0], - range=[0.0, 1.0], - type="linear", - showline=True, - ticks="inside", - nticks=3, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="x4", - side="left", - mirror="ticks", - ), - yaxis5=go.layout.YAxis( - domain=[0.27586206896551713, 0.72413793103448265], - range=[0.0, 1.0], - type="linear", - showline=True, - ticks="inside", - nticks=6, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="x5", - side="left", - mirror="ticks", - ), - yaxis6=go.layout.YAxis( - domain=[0.0, 0.17241379310344826], - range=[0.0, 1.0], - type="linear", - showline=True, - ticks="inside", - nticks=3, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="x6", - side="left", - mirror="ticks", - ), - yaxis7=go.layout.YAxis( - domain=[0.27586206896551713, 0.72413793103448265], - range=[0.0, 1.0], - type="linear", - showline=True, - ticks="inside", - nticks=6, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="x7", - side="left", - mirror="ticks", - ), - yaxis8=go.layout.YAxis( - domain=[0.0, 0.17241379310344826], - range=[0.0, 1.0], - type="linear", - showline=True, - ticks="inside", - nticks=3, - showgrid=False, - zeroline=False, - tickfont=dict(size=10.0), - anchor="x8", - side="left", - mirror="ticks", - ), - ), -) diff --git a/tests/test_subplots.py b/tests/test_subplots.py index 1cafc0e..837aac0 100644 --- a/tests/test_subplots.py +++ b/tests/test_subplots.py @@ -1,16 +1,35 @@ -from .utils import compare_dict, strip_dict_params +import matplotlib.pyplot as plt +import pytest +from matplotlib.gridspec import GridSpec + from matplotlylib import mpl_to_plotly -from .data.subplots import D, BLANK_SUBPLOTS -from matplotlib.gridspec import GridSpec -import matplotlib.pyplot as plt +# The axes below fill columns 1-5 and rows 0-3 of a 4x6 GridSpec whose gaps +# are 0.6 of a cell. Plotly's paper spans just those cells, so it is +# 5 cells + 4 gaps = 7.4 cells wide and 4 cells + 3 gaps = 5.8 cells high. +CELL_AND_GAP = 1.6 +PAPER_WIDTH = 7.4 +PAPER_HEIGHT = 5.8 + + +def x_domain(first_col, last_col): + start = (first_col - 1) * CELL_AND_GAP + end = (last_col - 1) * CELL_AND_GAP + 1 + return [start / PAPER_WIDTH, end / PAPER_WIDTH] + + +def y_domain(first_row, last_row): + # Rows count from the top, plotly's domains from the bottom + top = first_row * CELL_AND_GAP + bottom = last_row * CELL_AND_GAP + 1 + return [1 - bottom / PAPER_HEIGHT, 1 - top / PAPER_HEIGHT] def test_blank_subplots(): fig = plt.figure() gs = GridSpec(4, 6) ax1 = fig.add_subplot(gs[0, 1]) - ax1.plot(D["x1"], D["y1"]) + ax1.plot([0, 1], [1, 2]) fig.add_subplot(gs[1, 1]) fig.add_subplot(gs[2:, 1]) fig.add_subplot(gs[0, 2:]) @@ -19,13 +38,35 @@ def test_blank_subplots(): fig.add_subplot(gs[1:3, 4:]) fig.add_subplot(gs[3, 5]) gs.update(hspace=0.6, wspace=0.6) + plotly_fig = mpl_to_plotly(fig) - for data_no, data_dict in enumerate(plotly_fig["data"]): - d1, d2 = strip_dict_params( - data_dict, BLANK_SUBPLOTS["data"][data_no], ignore=["uid"] - ) - equivalent, msg = compare_dict(d1, d2) + # (first column, last column, first row, last row) of each subplot + cells = [ + (1, 1, 0, 0), + (1, 1, 1, 1), + (1, 1, 2, 3), + (2, 5, 0, 0), + (2, 3, 1, 2), + (2, 4, 3, 3), + (4, 5, 1, 2), + (5, 5, 3, 3), + ] + layout_keys = plotly_fig.layout.to_plotly_json() + assert len([k for k in layout_keys if k.startswith("xaxis")]) == len(cells) + assert len([k for k in layout_keys if k.startswith("yaxis")]) == len(cells) + for n, (first_col, last_col, first_row, last_row) in enumerate(cells, start=1): + xaxis = plotly_fig.layout[f"xaxis{n}"] + yaxis = plotly_fig.layout[f"yaxis{n}"] + assert list(xaxis.domain) == pytest.approx(x_domain(first_col, last_col)) + assert list(yaxis.domain) == pytest.approx(y_domain(first_row, last_row)) + suffix = "" if n == 1 else str(n) + assert xaxis.anchor == f"y{suffix}" + assert yaxis.anchor == f"x{suffix}" - equivalent, msg = compare_dict(plotly_fig["layout"], BLANK_SUBPLOTS["layout"]) - assert equivalent, msg + # The only line is on the first subplot + assert len(plotly_fig.data) == 1 + trace = plotly_fig.data[0] + assert (trace.xaxis, trace.yaxis) == ("x", "y") + assert list(trace.x) == [0, 1] + assert list(trace.y) == [1, 2] From a0eca956b2b7dfc813e29b78a75c3e03b8bf95bb Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Fri, 4 Dec 2026 03:36:14 +0000 Subject: [PATCH 22/23] Rewrite test_date_times and mark the pandas date bug as xfail test_normal_mpl_dates also checked matplotlib's internal day number for the first date, which counted from year 1 when the test was written and now counts from 1970. That says nothing about the conversion, so drop it and check the date axis, the marker mode and the x and y values. test_pandas_time_series_date_formatter finds a real bug: for a pandas time series plot, the converter sets a date axis but keeps matplotlib's day numbers as the x values, which plotly reads as milliseconds since 1970. plotly 7.2.0's built-in copy of matplotlylib has the same bug. Mark the test as a strict xfail until the bug is fixed, and drop its check of matplotlib's internal day number. --- tests/test_date_times.py | 61 +++++++++++++++++----------------------- 1 file changed, 26 insertions(+), 35 deletions(-) diff --git a/tests/test_date_times.py b/tests/test_date_times.py index 6492f54..4cbec40 100644 --- a/tests/test_date_times.py +++ b/tests/test_date_times.py @@ -1,62 +1,53 @@ import datetime +import matplotlib.pyplot as plt import pandas as pd +import pytest +from matplotlib.dates import date2num from matplotlylib import mpl_to_plotly -from matplotlib.dates import date2num -import matplotlib.pyplot as plt - def test_normal_mpl_dates(): - datetime_format = "%Y-%m-%d %H:%M:%S" - y = [1, 2, 3, 4] date_strings = [ "2010-01-04 00:00:00", "2010-01-04 10:00:00", "2010-01-04 23:00:59", "2010-01-05 00:00:00", ] + dates = [datetime.datetime.fromisoformat(s) for s in date_strings] - # 1. create datetimes from the strings - dates = [ - datetime.datetime.strptime(date_string, datetime_format) - for date_string in date_strings - ] - - # 2. create the mpl_dates from these datetimes - mpl_dates = date2num(dates) - - # make a figure in mpl + # Plot matplotlib date numbers on a date axis, as plot_date used to fig, ax = plt.subplots() ax.xaxis_date() - ax.plot(mpl_dates, y, "o") + ax.plot(date2num(dates), [1, 2, 3, 4], "o") - # convert this figure to plotly's graph_objs - pfig = mpl_to_plotly(fig) + plotly_fig = mpl_to_plotly(fig) - # we use the same format here, so we expect equality here - assert fig.axes[0].lines[0].get_xydata()[0][0] == 7.33776000e05 - assert tuple(pfig["data"][0]["x"]) == tuple(date_strings) + assert plotly_fig.layout.xaxis.type == "date" + assert len(plotly_fig.data) == 1 + trace = plotly_fig.data[0] + assert trace.mode == "markers" + assert list(trace.x) == date_strings + assert list(trace.y) == [1, 2, 3, 4] +@pytest.mark.xfail( + strict=True, + reason="pandas time series plots keep matplotlib's day numbers as x values " + "on a date axis, so plotly reads them as milliseconds since 1970", +) def test_pandas_time_series_date_formatter(): - ndays = 3 - x = pd.date_range("1/1/2001", periods=ndays, freq="D") - y = list(range(ndays)) - s = pd.DataFrame(y, columns=["a"]) + df = pd.DataFrame( + {"a": [0, 1, 2], "Date": pd.date_range("2001-01-01", periods=3, freq="D")} + ) + fig = df.plot(x="Date").figure - s["Date"] = x - fig = s.plot(x="Date").figure - pfig = mpl_to_plotly(fig) + plotly_fig = mpl_to_plotly(fig) - expected_x = ( + assert plotly_fig.layout.xaxis.type == "date" + assert list(plotly_fig.data[0].x) == [ "2001-01-01 00:00:00", "2001-01-02 00:00:00", "2001-01-03 00:00:00", - ) - expected_x0 = 11323.0 # this is floating point days since epoch - - x0 = fig.axes[0].lines[0].get_xydata()[0][0] - assert x0 == expected_x0 - assert pfig["data"][0]["x"] == expected_x + ] From 5f11856deab3cb372384d8e4631020b064b49ef2 Mon Sep 17 00:00:00 2001 From: Roberto Moura Date: Fri, 4 Dec 2026 03:39:26 +0000 Subject: [PATCH 23/23] Remove the unused tests/utils.py compare_dict, strip_dict_params and is_num_list were only used by the full-figure snapshot comparisons, which the ported tests no longer make. --- tests/utils.py | 75 -------------------------------------------------- 1 file changed, 75 deletions(-) delete mode 100644 tests/utils.py diff --git a/tests/utils.py b/tests/utils.py deleted file mode 100644 index 6ba836e..0000000 --- a/tests/utils.py +++ /dev/null @@ -1,75 +0,0 @@ -import copy -from numbers import Number as Num - -import pytest - - -def compare_dict(dict1, dict2, equivalent=True, msg="", tol=10e-8): - for key in dict1: - if key not in dict2: - return ( - False, - "{0} should be {1}".format(list(dict1.keys()), list(dict2.keys())), - ) - for key in dict1: - if isinstance(dict1[key], dict): - equivalent, msg = compare_dict(dict1[key], dict2[key], tol=tol) - elif isinstance(dict1[key], Num) and isinstance(dict2[key], Num): - if dict1[key] != pytest.approx(dict2[key], abs=tol): - return ( - False, - "['{0}'] = {1} should be {2}".format(key, dict1[key], dict2[key]), - ) - elif is_num_list(dict1[key]) and is_num_list(dict2[key]): - if dict1[key] != pytest.approx(dict2[key], abs=tol): - return ( - False, - "['{0}'] = {1} should be {2}".format(key, dict1[key], dict2[key]), - ) - elif not (dict1[key] == dict2[key]): - return ( - False, - "['{0}'] = {1} should be {2}".format(key, dict1[key], dict2[key]), - ) - if not equivalent: - return False, "['{0}']".format(key) + msg - return equivalent, msg - - -def strip_dict_params(d1, d2, ignore=["uid"]): - """ - Removes `ignore` params from d1 and/or d2 if they exist - then returns stripped dictionaries - - :param (list|tuple) ignore: sequence of key names as - strings that are removed from both d1 and d2 if - they exist - """ - # deep copy d1 and d2 - if "to_plotly_json" in dir(d1): - d1_copy = copy.deepcopy(d1.to_plotly_json()) - else: - d1_copy = copy.deepcopy(d1) - - if "to_plotly_json" in dir(d2): - d2_copy = copy.deepcopy(d2.to_plotly_json()) - else: - d2_copy = copy.deepcopy(d2) - - for key in ignore: - if key in d1_copy.keys(): - del d1_copy[key] - if key in d2_copy.keys(): - del d2_copy[key] - - return d1_copy, d2_copy - - -def is_num_list(item): - try: - for thing in item: - if not isinstance(thing, Num): - raise TypeError - except TypeError: - return False - return True