plotly.py icon indicating copy to clipboard operation
plotly.py copied to clipboard

Add matplotlib lines+markers plot conversion test

Open robertoffmoura opened this issue 7 months ago • 3 comments

Hi, I'm proposing a fix to an edge case where conversion from matplotlib to plotly would break when converting a "lines+markers" plot with a legend. The issue happens because go.layout.Shape is not expecting "symbol" or "size" properties. My proposed fix is to ignore those two properties for "lines" type legend shapes. Please let me know if another fix would be more appropriate.

Thanks

Code PR

  • [X] I have read through the contributing notes and understand the structure of the package. In particular, if my PR modifies code of plotly.graph_objects, my modifications concern the codegen files and not generated files.
  • [X] I have added tests (if submitting a new feature or correcting a bug) or modified existing tests.
  • [X] For a new feature, I have added documentation examples in an existing or new tutorial notebook (please see the doc checklist as well).
  • [X] I have added a CHANGELOG entry if fixing/changing/adding anything substantial.
  • [X] For a new feature or a change in behaviour, I have updated the relevant docstrings in the code to describe the feature or behaviour (please see the doc checklist as well).

robertoffmoura avatar Jun 17 '25 12:06 robertoffmoura

Hi @robertoffmoura, could you explain the issue in a little more detail and provide an example of a plot that fails currently (expected output vs. actual output)? That will help me evaluate this fix.

Thank you for the contribution!

emilykl avatar Oct 01 '25 21:10 emilykl

Hi @emilykl, Please see below the error we get if we run the tests I added in this commit without the changes I made to renderer.py:

=========================================================================================== test session starts ===========================================================================================
platform linux -- Python 3.12.0, pytest-8.4.0, pluggy-1.6.0
configfile: pyproject.toml
plugins: anyio-4.3.0
collected 1 item                                                                                                                                                                                          

plotly/matplotlylib/tests/test_renderer.py F                                                                                                                                                        [100%]

================================================================================================ FAILURES =================================================================================================
_____________________________________________________________________________________ test_lines_markers_legend_plot ______________________________________________________________________________________

    def test_lines_markers_legend_plot():
        x = [0, 1]
        y = [0, 1]
        label = "label"
        plt.figure()
        plt.plot(x, y, "o-", label=label)
        plt.legend()
    
>       plotly_fig = tls.mpl_to_plotly(plt.gcf())
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

plotly/matplotlylib/tests/test_renderer.py:14: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
plotly/tools.py:104: in mpl_to_plotly
    matplotlylib.Exporter(renderer).run(fig)
plotly/matplotlylib/mplexporter/exporter.py:54: in run
    self.crawl_fig(fig)
plotly/matplotlylib/mplexporter/exporter.py:125: in crawl_fig
    self.crawl_ax(ax)
plotly/matplotlylib/mplexporter/exporter.py:156: in crawl_ax
    self.crawl_legend(ax, legend)
plotly/matplotlylib/mplexporter/exporter.py:182: in crawl_legend
    self.draw_line(ax, child, force_trans=ax.transAxes)
plotly/matplotlylib/mplexporter/exporter.py:206: in draw_line
    self.renderer.draw_marked_line(
plotly/matplotlylib/renderer.py:504: in draw_marked_line
    self.draw_legend_shapes(mode=mode, shape=shape, **props)
plotly/matplotlylib/renderer.py:373: in draw_legend_shapes
    legend_shape = go.layout.Shape(
plotly/graph_objs/layout/_shape.py:1286: in __init__
    self._process_kwargs(**dict(arg, **kwargs))
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = layout.Shape({
    'fillcolor': '#1F77B4',
    'line': {'color': '#1F77B4', 'width': 1.0},
    'opacity': 1,
    'type...f': 'paper',
    'y0': np.float64(0.9695701058201058),
    'y1': np.float64(0.9695701058201058),
    'yref': 'paper'
})
kwargs = {'size': 6.0, 'symbol': 'circle'}, k = 'symbol', v = 'circle'
err = ValueError('Invalid property specified for object of type plotly.graph_objs.layout.Shape: \'symbol\'\n\nDid you mean "...elative to data or plot\n            fraction.\n        \nDid you mean "label"?\n\nBad property path:\nsymbol\n^^^^^^')

    def _process_kwargs(self, **kwargs):
        """
        Process any extra kwargs that are not predefined as constructor params
        """
        for k, v in kwargs.items():
            err = _check_path_in_prop_tree(self, k, error_cast=ValueError)
            if err is None:
                # e.g. underscore kwargs like marker_line_color
                self[k] = v
            elif not self._validate:
                # Set extra property as-is
                self[k] = v
            elif not self._skip_invalid:
>               raise err
E               ValueError: Invalid property specified for object of type plotly.graph_objs.layout.Shape: 'symbol'
E               
[...]
E               Did you mean "label"?
E               
E               Bad property path:
E               symbol
E               ^^^^^^

plotly/basedatatypes.py:4451: ValueError
============================================================================================ warnings summary =============================================================================================
plotly/conftest.py:4
  /plotly.py/plotly/conftest.py:4: PytestRemovedIn9Warning: The (path: py.path.local) argument is deprecated, please use (collection_path: pathlib.Path)
  see https://docs.pytest.org/en/latest/deprecations.html#py-path-local-arguments-for-hooks-replaced-with-pathlib-path
    def pytest_ignore_collect(path):

plotly/matplotlylib/tests/test_renderer.py::test_lines_markers_legend_plot
plotly/matplotlylib/tests/test_renderer.py::test_lines_markers_legend_plot
  /plotly.py/plotly/matplotlylib/mplexporter/utils.py:293: MatplotlibDeprecationWarning:
  
  The converter attribute was deprecated in Matplotlib 3.10 and will be removed in 3.12. Use get_converter and set_converter methods instead.

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
========================================================================================= short test summary info =========================================================================================
FAILED plotly/matplotlylib/tests/test_renderer.py::test_lines_markers_legend_plot - ValueError: Invalid property specified for object of type plotly.graph_objs.layout.Shape: 'symbol'
====================================================================================== 1 failed, 3 warnings in 1.09s ======================================================================================

robertoffmoura avatar Oct 09 '25 14:10 robertoffmoura

Hi @emilykl, You're right, after rebasing this branch on top of this, the issue is no longer there. I still think we should add a test for the lines+markers plot, so I renamed this PR.

robertoffmoura avatar Oct 09 '25 15:10 robertoffmoura