POKEMONKENG 2024-08-14 23:35 采纳率: 21.4%
浏览 10
已结题

python culfflinks怎么画图

python使用cufflinks时画图为什么会出现错误?
代码为

import pandas as pd
import cufflinks as cf
import plotly.offline as plyo
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import plotly.offline as pyo
import plotly.io as pio
cf.set_config_file(offline=True)
plyo.init_notebook_mode(connected=True)
a=np.random.standard_normal((250,5)).cumsum(axis=0)
index=pd.date_range('2019-1-1',freq='B',periods=len(a))
df=pd.DataFrame(100+5*a,columns=list('abcde'),index=index)
print(df.head())
df.iplot(kind = 'bar',title= '示例', xTitle = 'X轴', yTitle = 'Y轴',color='aliceblue')
pyo.init_notebook_mode()

运行完出现一堆错误:
ValueError:
Invalid value of type 'builtins.str' received for the 'color' property of bar.marker.line
Received value: 'rgba(240, 248, 255, 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
  - A number that will be interpreted as a color
    according to bar.marker.line.colorscale
  - A list or array of any of the above

这个到底怎么才能画出图,网上没人说
更详细错误为

C:\Users\pilibao\AppData\Local\Programs\Python\Python312\Lib\site-packages\cufflinks\plotlytools.py:117: FutureWarning:

DatetimeIndex.format is deprecated and will be removed in a future version. Convert using index.astype(str) or index.map(formatter) instead.

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[2], line 2
      1 color='aliceblue'
----> 2 plyo.iplot(df.iplot(kind = 'bar',title= '示例', xTitle = 'X轴', yTitle = 'Y轴',color=color))
      3 pyo.init_notebook_mode()

File ~\AppData\Local\Programs\Python\Python312\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 ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\cufflinks\plotlytools.py:159, 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)
    157             lines[key]["fillcolor"]=to_rgba(colors[key],kwargs['opacity'] if 'opacity' in kwargs else .3        )
    158 if 'bar' in kind:
--> 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]

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\plotly\graph_objs\_bar.py:3313, in Bar.__init__(self, arg, alignmentgroup, base, basesrc, cliponaxis, constraintext, customdata, customdatasrc, dx, dy, error_x, error_y, hoverinfo, hoverinfosrc, hoverlabel, hovertemplate, hovertemplatesrc, hovertext, hovertextsrc, ids, idssrc, insidetextanchor, insidetextfont, legend, legendgroup, legendgrouptitle, legendrank, legendwidth, marker, meta, metasrc, name, offset, offsetgroup, offsetsrc, opacity, orientation, outsidetextfont, selected, selectedpoints, showlegend, stream, text, textangle, textfont, textposition, textpositionsrc, textsrc, texttemplate, texttemplatesrc, uid, uirevision, unselected, visible, width, widthsrc, x, x0, xaxis, xcalendar, xhoverformat, xperiod, xperiod0, xperiodalignment, xsrc, y, y0, yaxis, ycalendar, yhoverformat, yperiod, yperiod0, yperiodalignment, ysrc, zorder, **kwargs)
   3311 _v = marker if marker is not None else _v
   3312 if _v is not None:
-> 3313     self["marker"] = _v
   3314 _v = arg.pop("meta", None)
   3315 _v = meta if meta is not None else _v

File ~\AppData\Local\Programs\Python\Python312\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 ~\AppData\Local\Programs\Python\Python312\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 ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\_plotly_utils\basevalidators.py:2511, in CompoundValidator.validate_coerce(self, v, skip_invalid, _validate)
   2508     v = self.data_class()
   2510 elif isinstance(v, dict):
-> 2511     v = self.data_class(v, skip_invalid=skip_invalid, _validate=_validate)
   2513 elif isinstance(v, self.data_class):
   2514     # Copy object
   2515     v = self.data_class(v)

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\plotly\graph_objs\bar\_marker.py:1218, in Marker.__init__(self, arg, autocolorscale, cauto, cmax, cmid, cmin, color, coloraxis, colorbar, colorscale, colorsrc, cornerradius, line, opacity, opacitysrc, pattern, reversescale, showscale, **kwargs)
   1216 _v = line if line is not None else _v
   1217 if _v is not None:
-> 1218     self["line"] = _v
   1219 _v = arg.pop("opacity", None)
   1220 _v = opacity if opacity is not None else _v

File ~\AppData\Local\Programs\Python\Python312\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 ~\AppData\Local\Programs\Python\Python312\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 ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\_plotly_utils\basevalidators.py:2511, in CompoundValidator.validate_coerce(self, v, skip_invalid, _validate)
   2508     v = self.data_class()
   2510 elif isinstance(v, dict):
-> 2511     v = self.data_class(v, skip_invalid=skip_invalid, _validate=_validate)
   2513 elif isinstance(v, self.data_class):
   2514     # Copy object
   2515     v = self.data_class(v)

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\plotly\graph_objs\bar\marker\_line.py:626, in Line.__init__(self, arg, autocolorscale, cauto, cmax, cmid, cmin, color, coloraxis, colorscale, colorsrc, reversescale, width, widthsrc, **kwargs)
    624 _v = color if color is not None else _v
    625 if _v is not None:
--> 626     self["color"] = _v
    627 _v = arg.pop("coloraxis", None)
    628 _v = coloraxis if coloraxis is not None else _v

File ~\AppData\Local\Programs\Python\Python312\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 ~\AppData\Local\Programs\Python\Python312\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 ~\AppData\Local\Programs\Python\Python312\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 ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\_plotly_utils\basevalidators.py:1410, in ColorValidator.validate_coerce(self, v, should_raise)
   1408     validated_v = self.vc_scalar(v)
   1409     if validated_v is None and should_raise:
-> 1410         self.raise_invalid_val(v)
   1412     v = validated_v
   1414 return v

File ~\AppData\Local\Programs\Python\Python312\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         )

  • 写回答

16条回答 默认 最新

  • Roc-xb 后端领域优质创作者 2024-08-15 00:16
    关注

    img

    
    import pandas as pd
    import numpy as np
    import plotly.express as px
    
    # 生成随机数据
    a = np.random.standard_normal((250, 5)).cumsum(axis=0)
    index = pd.date_range('2019-1-1', freq='B', periods=len(a))
    
    # 创建 DataFrame
    df = pd.DataFrame(100 + 5 * a, columns=list('abcde'), index=index)
    print(df.head())
    
    # 将 DatetimeIndex 转换为字符串以避免弃用警告
    df.index = df.index.astype(str)
    
    # 重新组织数据以便于绘图
    df_reset = df.reset_index().melt(id_vars=['index'], var_name='Variable', value_name='Value')
    
    # 使用 plotly.express 进行绘图
    fig = px.bar(df_reset, x='index', y='Value', color='Variable', title='示例', labels={'index': 'X轴', 'Value': 'Y轴'})
    fig.show()
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(15条)

报告相同问题?

问题事件

  • 系统已结题 8月23日
  • 已采纳回答 8月15日
  • 赞助了问题酬金15元 8月14日
  • 创建了问题 8月14日

悬赏问题

  • ¥15 关于#matlab#的问题:有没有什么其他办法能够保证不退出进程(相关搜索:matlab调用)
  • ¥15 依据报错在原代吗格式的基础上解决问题
  • ¥15 在虚拟机中安装flash code
  • ¥15 单片机stm32f10x编写光敏电阻调节3.3伏大功率灯亮度(光强越大灯越暗,白天正常光强灯不亮,使用ADC,PWM等模块)望各位找一下错误或者提供一个可实现功能的代码
  • ¥20 verilog状态机方法流水灯
  • ¥15 pandas代码实现不了意图
  • ¥15 GD32H7 从存储器到外设SPI传输数据无法重复启用DMA
  • ¥25 LT码在高斯信道下的误码率仿真
  • ¥45 渲染完成之后将物体的材质贴图改变,自动化进行这个操作
  • ¥15 yolov5目标检测并显示目标出现的时间或视频帧