Plotly and cufflinks not working in Anaconda

邮差的信 提交于 2019-12-23 13:21:01

问题


I have been doing a course on data science and machine learning and in one of the lesson, it asked me to download and use plotly and cufflinks. I downloaded and installed them successfully, I have imported them successfully as well. But while trying to use them using iplot, it's giving me an error. Below I have attached screenshots of the error so I want to know how to solve this error and use plotly and cufflinks without any issue.

The code that I wrote:

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)

The error that I get:

---------------------------------------------------------------------------
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

回答1:


What you would get when executed following code?

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)

With plotly.offline.plot everything work fine but you need only plotly.plotly.iplot as I think. After googling I found the possible solution to that - just downgrade your plotly version:

pip uninstall plotly
pip install plotly==2.7.0

I checked the latest version plotly - it is 3.1.1 and this bug also is here. So I am suppose that using version plotly<3.0.0 can solve your problem




回答2:


Updated solution as of 2019:

This is an error that happens if you have cufflinks version 0.13 or older which was not compatible with plotly 3.0. This may happen because you installed from conda or another source and not with pip.

To solve it, run:

pip install cufflinks --upgrade



回答3:


To sum up as told by @Idodo you have to write the following lines of code in your "Anaconda Prompt" please open this by selecting as an administrator.

for the plotly library

conda install -c plotly plotly 

for the cufflinks library

conda install -c conda-forge python-cufflinks 

then upgrade the cufflinks

pip install cufflinks --upgrade


来源:https://stackoverflow.com/questions/51998661/plotly-and-cufflinks-not-working-in-anaconda

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!