python - Plotly 和袖扣在 Anaconda 中不起作用
问题描述
我一直在上一门关于数据科学和机器学习的课程,在其中一课中,它要求我下载并使用 plotly 和 cufflinks。我成功下载并安装了它们,我也成功导入了它们。但是在尝试使用 iplot 使用它们时,它给了我一个错误。下面我附上了错误的屏幕截图,所以我想知道如何解决这个错误并使用 plotly 和 cufflinks 没有任何问题。
我写的代码:
import pandas as pd
import numpy as np
%matplotlib inline
from plotly import __version__
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
print(__version__)
init_notebook_mode(connected=True)
cf.go_offline()
df = pd.DataFrame(np.random.randn(100,4),columns='A B C D'.split())
df.iplot(kind='scatter',x='A',y='B',mode='markers',size=10)
我得到的错误:
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-10-d68919405364> in <module>() ----> 1 df.iplot(kind='scatter',x='A',y='B',mode='markers',size=10) C:\ProgramData\Anaconda3\lib\site-packages\cufflinks\plotlytools.py 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) 761 bargap=bargap,bargroupgap=bargroupgap,annotations=annotations,gridcolor=gridcolor, 762 dimensions=dimensions, --> 763 zerolinecolor=zerolinecolor,margin=margin,is3d='3d' in kind,**l_kwargs) 764 765 if not data: C:\ProgramData\Anaconda3\lib\site-packages\cufflinks\tools.py in getLayout(kind, theme, title, xTitle, yTitle, zTitle, barmode, bargap, bargroupgap, margin, dimensions, width, height, annotations, is3d, **kwargs) 199 200 theme_data = getTheme(theme) --> 201 layout=go.Layout(theme_data['layout']) 202 layout['xaxis1'].update({'title':xTitle}) 203 layout['yaxis1'].update({'title':yTitle}) C:\ProgramData\Anaconda3\lib\site-packages\plotly\graph_objs\_layout.py in __init__(self, arg, angularaxis, annotations, autosize, bargap, bargroupgap, barmode, barnorm, boxgap, boxgroupgap, boxmode, calendar, colorway, datarevision, direction, dragmode, font, geo, grid, height, hiddenlabels, hiddenlabelssrc, hidesources, hoverdistance, hoverlabel, hovermode, images, legend, mapbox, margin, orientation, paper_bgcolor, plot_bgcolor, polar, radialaxis, scene, selectdirection, separators, shapes, showlegend, sliders, spikedistance, template, ternary, title, titlefont, updatemenus, violingap, violingroupgap, violinmode, width, xaxis, yaxis, **kwargs) 3735 self.images = images if images is not None else _v 3736 _v = arg.pop('legend', None) -> 3737 self.legend = legend if legend is not None else _v 3738 _v = arg.pop('mapbox', None) 3739 self.mapbox = mapbox if mapbox is not None else _v C:\ProgramData\Anaconda3\lib\site-packages\plotly\basedatatypes.py in __setattr__(self, prop, value) 3601 if match is None: 3602 # Set as ordinary property -> 3603 super(BaseLayoutHierarchyType, self).__setattr__(prop, value) 3604 else: 3605 # Set as subplotid property C:\ProgramData\Anaconda3\lib\site-packages\plotly\basedatatypes.py in __setattr__(self, prop, value) 2702 prop in self._validators): 2703 # Let known properties and private properties through -> 2704 super(BasePlotlyType, self).__setattr__(prop, value) 2705 else: 2706 # Raise error on unknown public properties C:\ProgramData\Anaconda3\lib\site-packages\plotly\graph_objs\_layout.py in legend(self, val) 1224 @legend.setter 1225 def legend(self, val): -> 1226 self['legend'] = val 1227 1228 # mapbox C:\ProgramData\Anaconda3\lib\site-packages\plotly\basedatatypes.py in __setitem__(self, prop, value) 3587 if match is None: 3588 # Set as ordinary property -> 3589 super(BaseLayoutHierarchyType, self).__setitem__(prop, value) 3590 else: 3591 # Set as subplotid property C:\ProgramData\Anaconda3\lib\site-packages\plotly\basedatatypes.py in __setitem__(self, prop, value) 2665 # ### Handle compound property ### 2666 if isinstance(validator, CompoundValidator): -> 2667 self._set_compound_prop(prop, value) 2668 2669 # ### Handle compound array property ### C:\ProgramData\Anaconda3\lib\site-packages\plotly\basedatatypes.py in _set_compound_prop(self, prop, val) 2963 validator = self._validators.get(prop) 2964 # type: BasePlotlyType -> 2965 val = validator.validate_coerce(val) 2966 2967 # Save deep copies of current and new states C:\ProgramData\Anaconda3\lib\site-packages\_plotly_utils\basevalidators.py in validate_coerce(self, v) 1790 1791 elif isinstance(v, dict): -> 1792 v = self.data_class(**v) 1793 1794 elif isinstance(v, self.data_class): C:\ProgramData\Anaconda3\lib\site-packages\plotly\graph_objs\layout\_legend.py in __init__(self, arg, bgcolor, bordercolor, borderwidth, font, orientation, tracegroupgap, traceorder, x, xanchor, y, yanchor, **kwargs) 500 # ---------------------------------- 501 _v = arg.pop('bgcolor', None) --> 502 self.bgcolor = bgcolor if bgcolor is not None else _v 503 _v = arg.pop('bordercolor', None) 504 self.bordercolor = bordercolor if bordercolor is not None else _v C:\ProgramData\Anaconda3\lib\site-packages\plotly\basedatatypes.py in __setattr__(self, prop, value) 2702 prop in self._validators): 2703 # Let known properties and private properties through -> 2704 super(BasePlotlyType, self).__setattr__(prop, value) 2705 else: 2706 # Raise error on unknown public properties C:\ProgramData\Anaconda3\lib\site-packages\plotly\graph_objs\layout\_legend.py in bgcolor(self, val) 62 @bgcolor.setter 63 def bgcolor(self, val): ---> 64 self['bgcolor'] = val 65 66 # bordercolor C:\ProgramData\Anaconda3\lib\site-packages\plotly\basedatatypes.py in __setitem__(self, prop, value) 2674 # ### Handle simple property ### 2675 else: -> 2676 self._set_prop(prop, value) 2677 2678 # Handle non-scalar case C:\ProgramData\Anaconda3\lib\site-packages\plotly\basedatatypes.py in _set_prop(self, prop, val) 2904 # ------------ 2905 validator = self._validators.get(prop) -> 2906 val = validator.validate_coerce(val) 2907 2908 # val is None C:\ProgramData\Anaconda3\lib\site-packages\_plotly_utils\basevalidators.py in validate_coerce(self, v, should_raise) 1068 validated_v = self.vc_scalar(v) 1069 if validated_v is None and should_raise: -> 1070 self.raise_invalid_val(v) 1071 1072 v = validated_v C:\ProgramData\Anaconda3\lib\site-packages\_plotly_utils\basevalidators.py in raise_invalid_val(self, v) 214 typ=type_str(v), 215 v=repr(v), --> 216 valid_clr_desc=self.description())) 217 218 def raise_invalid_elements(self, invalid_els): ValueError: Invalid value of type 'builtins.str' received for the 'bgcolor' property of layout.legend Received value: 'pearl02' The 'bgcolor' 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, 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
解决方案
执行以下代码会得到什么?
import plotly
import plotly.plotly as py
import plotly.graph_objs as go
import numpy as np
import pandas as pd
import numpy as np
%matplotlib inline
from plotly import __version__
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import cufflinks as cf
print(__version__)
init_notebook_mode(connected=True)
cf.go_offline()
df = pd.DataFrame(np.random.randn(100,4),columns='A B C D'.split())
trace = go.Scatter(x = df['A'], y = df['B'], mode = 'markers')
data = [trace]
fig = go.Figure(data=data)
plotly.offline.plot(fig)
plotly.offline.plot
一切正常,但你只需要我plotly.plotly.iplot
想的。谷歌搜索后,我找到了可能的解决方案- 只需降级您的情节版本:
pip uninstall plotly
pip install plotly==2.7.0
我检查了最新版本plotly
- 它是 3.1.1,这个错误也在这里。所以我想使用版本 plotly<3.0.0 可以解决你的问题
推荐阅读
- python - 如何使用 ipywidgets fileupload 上传大文件?
- javascript - 在 JSX 中访问 DOM 元素
- python - 如何从单个 XML 元素中提取文本?
- jstree - 在页面启动时以编程方式在 jsTree 中选择节点的问题
- reactjs - Electron Forge、React 等构建已经疯狂
- python - Python List of Lists 如何按索引删除 adjListCopy 中的列表元素?
- c# - Web api响应中的列表与数据表
- r - r Shiny selectinput:防止 selectInput 小部件自动将列表的选定元素推送到窗口的最底部
- google-app-engine - 找不到来自本地模块的包“找不到提供包的模块”
- amazon-ec2 - 使用并行工具在 PBS 中运行数百万个列表