Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support range() as keyword argument for go.Scatter #1798

Open
dniku opened this issue Oct 4, 2019 · 3 comments · May be fixed by #4636
Open

support range() as keyword argument for go.Scatter #1798

dniku opened this issue Oct 4, 2019 · 3 comments · May be fixed by #4636
Labels
feature something new P3 not needed for current cycle

Comments

@dniku
Copy link

dniku commented Oct 4, 2019

In Jupyter notebook:

import plotly.graph_objects as go
go.Figure(go.Scatter(x=range(3), y=[3, 2, 1]))

Output:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-1-be3f9396b95f> in <module>
      1 import plotly.graph_objects as go
----> 2 go.Figure(go.Scatter(x=range(3), y=[3, 2, 1]))

/usr/lib/python3.7/site-packages/plotly/graph_objs/__init__.py in __init__(self, arg, cliponaxis, connectgaps, customdata, customdatasrc, dx, dy, error_x, error_y, fill, fillcolor, groupnorm, hoverinfo, hoverinfosrc, hoverlabel, hoveron, hovertemplate, hovertemplatesrc, hovertext, hovertextsrc, ids, idssrc, legendgroup, line, marker, meta, metasrc, mode, name, opacity, orientation, r, rsrc, selected, selectedpoints, showlegend, stackgaps, stackgroup, stream, t, text, textfont, textposition, textpositionsrc, textsrc, tsrc, uid, uirevision, unselected, visible, x, x0, xaxis, xcalendar, xsrc, y, y0, yaxis, ycalendar, ysrc, **kwargs)
  39689         self["visible"] = visible if visible is not None else _v
  39690         _v = arg.pop("x", None)
> 39691         self["x"] = x if x is not None else _v
  39692         _v = arg.pop("x0", None)
  39693         self["x0"] = x0 if x0 is not None else _v

/usr/lib/python3.7/site-packages/plotly/basedatatypes.py in __setitem__(self, prop, value)
   3351             # ### Handle simple property ###
   3352             else:
-> 3353                 self._set_prop(prop, value)
   3354 
   3355         # Handle non-scalar case

/usr/lib/python3.7/site-packages/plotly/basedatatypes.py in _set_prop(self, prop, val)
   3634                 return
   3635             else:
-> 3636                 raise err
   3637 
   3638         # val is None

/usr/lib/python3.7/site-packages/plotly/basedatatypes.py in _set_prop(self, prop, val)
   3629         validator = self._validators.get(prop)
   3630         try:
-> 3631             val = validator.validate_coerce(val)
   3632         except ValueError as err:
   3633             if self._skip_invalid:

/usr/lib/python3.7/site-packages/_plotly_utils/basevalidators.py in validate_coerce(self, v)
    387             v = to_scalar_or_list(v)
    388         else:
--> 389             self.raise_invalid_val(v)
    390         return v
    391 

/usr/lib/python3.7/site-packages/_plotly_utils/basevalidators.py in raise_invalid_val(self, v, inds)
    281                 typ=type_str(v),
    282                 v=repr(v),
--> 283                 valid_clr_desc=self.description(),
    284             )
    285         )

ValueError: 
    Invalid value of type 'builtins.range' received for the 'x' property of scatter
        Received value: range(0, 3)

    The 'x' property is an array that may be specified as a tuple,
    list, numpy array, or pandas Series

Plotly is installed from Arch Linux AUR, based on version 4.1.0, built using this script.

@nicolaskruchten
Copy link
Contributor

That's correct, as per the error message: range() doesn't return a list in Python 3, it returns a generator.

@dniku
Copy link
Author

dniku commented Oct 4, 2019

Technically, this is not exactly the case: range() is a special object, not a generator. In particular, it has __len__() and random access:

In [1]: a = range(1, 20, 3)                                                                                                                                                                                                                                                                                                                                                                                                          

In [2]: len(a)                                                                                                                                                                                                                                                                                                                                                                                                                       
Out[2]: 7

In [3]: a[3]                                                                                                                                                                                                                                                                                                                                                                                                                         
Out[3]: 10

Hence, it walks like a list and quacks like a list, so it should be relatively straightforward to add support for it.

@gvwilson
Copy link
Contributor

Hi - we are currently trying to tidy up Plotly's public repositories to help us focus our efforts on things that will help users most. Since this issue has been sitting for several years, I'm going to close it. If it's still a concern, we'd be grateful if you could open a new issue (with a short reproducible example if appropriate) so that we can add it to our backlog. Thanks for your help - @gvwilson

dniku added a commit to dniku/plotly.py that referenced this issue Jun 15, 2024
Fixes plotly#1798 (incorrectly closed during a recent cleanup).

Allows range() to be passed where simple arrays are expected.

Previously the following code

```python
import plotly.graph_objects as go
go.Figure(go.Scatter(x=range(3), y=[3, 2, 1]))
```

failed with

```
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-1-be3f9396b95f> in <cell line: 2>()
      1 import plotly.graph_objects as go
----> 2 go.Figure(go.Scatter(x=range(3), y=[3, 2, 1]))

5 frames
/usr/local/lib/python3.10/dist-packages/plotly/graph_objs/_scatter.py in __init__(self, arg, alignmentgroup, cliponaxis, connectgaps, customdata, customdatasrc, dx, dy, error_x, error_y, fill, fillcolor, fillpattern, groupnorm, hoverinfo, hoverinfosrc, hoverlabel, hoveron, hovertemplate, hovertemplatesrc, hovertext, hovertextsrc, ids, idssrc, legend, legendgroup, legendgrouptitle, legendrank, legendwidth, line, marker, meta, metasrc, mode, name, offsetgroup, opacity, orientation, selected, selectedpoints, showlegend, stackgaps, stackgroup, stream, text, textfont, textposition, textpositionsrc, textsrc, texttemplate, texttemplatesrc, uid, uirevision, unselected, visible, x, x0, xaxis, xcalendar, xhoverformat, xperiod, xperiod0, xperiodalignment, xsrc, y, y0, yaxis, ycalendar, yhoverformat, yperiod, yperiod0, yperiodalignment, ysrc, **kwargs)
   3476         _v = x if x is not None else _v
   3477         if _v is not None:
-> 3478             self["x"] = _v
   3479         _v = arg.pop("x0", None)
   3480         _v = x0 if x0 is not None else _v

/usr/local/lib/python3.10/dist-packages/plotly/basedatatypes.py in __setitem__(self, prop, value)
   4871                 # ### Handle simple property ###
   4872                 else:
-> 4873                     self._set_prop(prop, value)
   4874             else:
   4875                 # Make sure properties dict is initialized

/usr/local/lib/python3.10/dist-packages/plotly/basedatatypes.py in _set_prop(self, prop, val)
   5215                 return
   5216             else:
-> 5217                 raise err
   5218 
   5219         # val is None

/usr/local/lib/python3.10/dist-packages/plotly/basedatatypes.py in _set_prop(self, prop, val)
   5210 
   5211         try:
-> 5212             val = validator.validate_coerce(val)
   5213         except ValueError as err:
   5214             if self._skip_invalid:

/usr/local/lib/python3.10/dist-packages/_plotly_utils/basevalidators.py in validate_coerce(self, v)
    401             v = to_scalar_or_list(v)
    402         else:
--> 403             self.raise_invalid_val(v)
    404         return v
    405 

/usr/local/lib/python3.10/dist-packages/_plotly_utils/basevalidators.py in raise_invalid_val(self, v, inds)
    285                 name += "[" + str(i) + "]"
    286 
--> 287         raise ValueError(
    288             """
    289     Invalid value of type {typ} received for the '{name}' property of {pname}

ValueError: 
    Invalid value of type 'builtins.range' received for the 'x' property of scatter
        Received value: range(0, 3)

    The 'x' property is an array that may be specified as a tuple,
    list, numpy array, or pandas Series
```

(tested via [Google Colab](https://colab.research.google.com/notebooks/empty.ipynb))

After this change, it is possible to use `range()` in this context.

A potential concern is Python 2 support — there, `range()` is a plain list. I have not tested this with Python 2.
@dniku dniku linked a pull request Jun 15, 2024 that will close this issue
@gvwilson gvwilson self-assigned this Jun 18, 2024
@gvwilson gvwilson reopened this Jun 18, 2024
@gvwilson gvwilson removed their assignment Aug 2, 2024
@gvwilson gvwilson added the P3 not needed for current cycle label Aug 12, 2024
@gvwilson gvwilson changed the title go.Scatter does not support range() as x kwarg support range() as keyword argument for go.Scatter Aug 12, 2024
@gvwilson gvwilson added the feature something new label Aug 12, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature something new P3 not needed for current cycle
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants