[Python] Invalid value of type 'builtins.str' received for the 'color' property of...

Discussão em 'Python' iniciado por Stack, Fevereiro 21, 2025.

  1. Stack

    Stack Membro Participativo

    I am using this set of imports

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    from chart_studio import plotly
    # import plotly.plotly as pl
    import plotly.graph_objs as go
    import plotly.offline as of
    import cufflinks as cf
    import datetime as dt
    %matplotlib inline


    of.init_notebook_mode(connected = True)
    cf.go_offline()


    And when i try to run this code

    df.iplot(kind='scatter',xTitle='Projects',
    yTitle='Donations',title='Projects vs Donations',
    symbol='x',colorscale='paired',mode='markers')


    **It throws error **

    ValueError Traceback (most recent call last)
    Cell In[94], line 1
    ----> 1 df.iplot(kind='scatter',xTitle='Projects',
    2 yTitle='Donations',title='Projects vs Donations',
    3 symbol='x',colorscale='paired',mode='markers')

    File ~\anaconda3\Lib\site-packages\cufflinks\plotlytools.py:839, in _iplot(self, kind, data, layout, filename, sharing, title, xTitle, yTitle, zTitle, theme, colors, colorscale, fill, width, dash, mode, interpolation, symbol, size, barmode, sortbars, bargap, bargroupgap, bins, histnorm, histfunc, orientation, boxpoints, annotations, keys, bestfit, bestfit_colors, mean, mean_colors, categories, x, y, z, text, gridcolor, zerolinecolor, margin, labels, values, secondary_y, secondary_y_title, subplots, shape, error_x, error_y, error_type, locations, lon, lat, asFrame, asDates, asFigure, asImage, dimensions, asPlot, asUrl, online, **kwargs)
    837 if not isinstance(text,list):
    838 text=self[text].values
    --> 839 data=df.to_iplot(colors=colors,colorscale=colorscale,kind=kind,interpolation=interpolation,fill=fill,width=width,dash=dash,sortbars=sortbars,keys=keys,
    840 bestfit=bestfit,bestfit_colors=bestfit_colors,mean=mean,mean_colors=mean_colors,asDates=asDates,mode=mode,symbol=symbol,size=size,
    841 text=text,**kwargs)
    842 trace_kw=check_kwargs(kwargs,TRACE_KWARGS)
    843 for trace in data:

    File ~\anaconda3\Lib\site-packages\cufflinks\plotlytools.py:161, in _to_iplot(self, colors, colorscale, kind, mode, interpolation, symbol, size, fill, width, dash, sortbars, keys, bestfit, bestfit_colors, opacity, mean, mean_colors, asDates, asTimestamp, text, **kwargs)
    159 lines_plotly=[Bar(lines[key]).to_plotly_json() for key in keys]
    160 else:
    --> 161 lines_plotly=[Scatter(lines[key]).to_plotly_json() for key in keys]
    162 for trace in lines_plotly:
    163 if isinstance(trace['name'],pd.Timestamp):

    File ~\anaconda3\Lib\site-packages\plotly\graph_objs\_scatter.py:3530, in Scatter.__init__(self, arg, alignmentgroup, cliponaxis, connectgaps, customdata, customdatasrc, dx, dy, error_x, error_y, fill, fillcolor, fillgradient, 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, zorder, **kwargs)
    3528 _v = line if line is not None else _v
    3529 if _v is not None:
    -> 3530 self["line"] = _v
    3531 _v = arg.pop("marker", None)
    3532 _v = marker if marker is not None else _v

    File ~\anaconda3\Lib\site-packages\plotly\basedatatypes.py:4860, in BasePlotlyType.__setitem__(self, prop, value)
    4858 # ### Handle compound property ###
    4859 if isinstance(validator, CompoundValidator):
    -> 4860 self._set_compound_prop(prop, value)
    4862 # ### Handle compound array property ###
    4863 elif isinstance(validator, (CompoundArrayValidator, BaseDataValidator)):

    File ~\anaconda3\Lib\site-packages\plotly\basedatatypes.py:5271, in BasePlotlyType._set_compound_prop(self, prop, val)
    5268 # Import value
    5269 # ------------
    5270 validator = self._get_validator(prop)
    -> 5271 val = validator.validate_coerce(val, skip_invalid=self._skip_invalid)
    5273 # Save deep copies of current and new states
    5274 # ------------------------------------------
    5275 curr_val = self._compound_props.get(prop, None)

    File ~\anaconda3\Lib\site-packages\_plotly_utils\basevalidators.py:2512, in CompoundValidator.validate_coerce(self, v, skip_invalid, _validate)
    2509 v = self.data_class()
    2511 elif isinstance(v, dict):
    -> 2512 v = self.data_class(v, skip_invalid=skip_invalid, _validate=_validate)
    2514 elif isinstance(v, self.data_class):
    2515 # Copy object
    2516 v = self.data_class(v)

    File ~\anaconda3\Lib\site-packages\plotly\graph_objs\scatter\_line.py:374, in Line.__init__(self, arg, backoff, backoffsrc, color, dash, shape, simplify, smoothing, width, **kwargs)
    372 _v = color if color is not None else _v
    373 if _v is not None:
    --> 374 self["color"] = _v
    375 _v = arg.pop("dash", None)
    376 _v = dash if dash is not None else _v

    File ~\anaconda3\Lib\site-packages\plotly\basedatatypes.py:4868, in BasePlotlyType.__setitem__(self, prop, value)
    4864 self._set_array_prop(prop, value)
    4866 # ### Handle simple property ###
    4867 else:
    -> 4868 self._set_prop(prop, value)
    4869 else:
    4870 # Make sure properties dict is initialized
    4871 self._init_props()

    File ~\anaconda3\Lib\site-packages\plotly\basedatatypes.py:5212, in BasePlotlyType._set_prop(self, prop, val)
    5210 return
    5211 else:
    -> 5212 raise err
    5214 # val is None
    5215 # -----------
    5216 if val is None:
    5217 # Check if we should send null update

    File ~\anaconda3\Lib\site-packages\plotly\basedatatypes.py:5207, in BasePlotlyType._set_prop(self, prop, val)
    5204 validator = self._get_validator(prop)
    5206 try:
    -> 5207 val = validator.validate_coerce(val)
    5208 except ValueError as err:
    5209 if self._skip_invalid:

    File ~\anaconda3\Lib\site-packages\_plotly_utils\basevalidators.py:1411, in ColorValidator.validate_coerce(self, v, should_raise)
    1409 validated_v = self.vc_scalar(v)
    1410 if validated_v is None and should_raise:
    -> 1411 self.raise_invalid_val(v)
    1413 v = validated_v
    1415 return v

    File ~\anaconda3\Lib\site-packages\_plotly_utils\basevalidators.py:296, in BaseValidator.raise_invalid_val(self, v, inds)
    293 for i in inds:
    294 name += "[" + str(i) + "]"
    --> 296 raise ValueError(
    297 """
    298 Invalid value of type {typ} received for the '{name}' property of {pname}
    299 Received value: {v}
    300
    301 {valid_clr_desc}""".format(
    302 name=name,
    303 pname=self.parent_name,
    304 typ=type_str(v),
    305 v=repr(v),
    306 valid_clr_desc=self.description(),
    307 )
    308 )

    ValueError:
    Invalid value of type 'builtins.str' received for the 'color' property of scatter.line
    Received value: 'rgba(166, 206, 227, np.float64(1.0))'

    The 'color' property is a color and may be specified as:
    - A hex string (e.g. '#ff0000')
    - An rgb/rgba string (e.g. 'rgb(255,0,0)')
    - An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
    - An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
    - A named CSS color:
    aliceblue, antiquewhite, aqua, aquamarine, azure,
    beige, bisque, black, blanchedalmond, blue,
    blueviolet, brown, burlywood, cadetblue,
    chartreuse, chocolate, coral, cornflowerblue,
    cornsilk, crimson, cyan, darkblue, darkcyan,
    darkgoldenrod, darkgray, darkgrey, darkgreen,
    darkkhaki, darkmagenta, darkolivegreen, darkorange,
    darkorchid, darkred, darksalmon, darkseagreen,
    darkslateblue, darkslategray, darkslategrey,
    darkturquoise, darkviolet, deeppink, deepskyblue,
    dimgray, dimgrey, dodgerblue, firebrick,
    floralwhite, forestgreen, fuchsia, gainsboro,
    ghostwhite, gold, goldenrod, gray, grey, green,
    greenyellow, honeydew, hotpink, indianred, indigo,
    ivory, khaki, lavender, lavenderblush, lawngreen,
    lemonchiffon, lightblue, lightcoral, lightcyan,
    lightgoldenrodyellow, lightgray, lightgrey,
    lightgreen, lightpink, lightsalmon, lightseagreen,
    lightskyblue, lightslategray, lightslategrey,
    lightsteelblue, lightyellow, lime, limegreen,
    linen, magenta, maroon, mediumaquamarine,
    mediumblue, mediumorchid, mediumpurple,
    mediumseagreen, mediumslateblue, mediumspringgreen,
    mediumturquoise, mediumvioletred, midnightblue,
    mintcream, mistyrose, moccasin, navajowhite, navy,
    oldlace, olive, olivedrab, orange, orangered,
    orchid, palegoldenrod, palegreen, paleturquoise,
    palevioletred, papayawhip, peachpuff, peru, pink,
    plum, powderblue, purple, red, rosybrown,
    royalblue, rebeccapurple, saddlebrown, salmon,
    sandybrown, seagreen, seashell, sienna, silver,
    skyblue, slateblue, slategray, slategrey, snow,
    springgreen, steelblue, tan, teal, thistle, tomato,
    turquoise, violet, wheat, white, whitesmoke,
    yellow, yellowgreen


    This is what I get (Output Image)

    I tried to change the versions of the plotly module to older one. Also with this set of code the required graph can be obtained but i want to use the intractive plot (iplot) for better and detailed graphs.

    df.plot.scatter(xlabel='Projects', ylabel='Donations', title='Projects vs Donations' , x='Projects', y='Donations')
    plt.show()

    Continue reading...

Compartilhe esta Página