我一直在学习用有日期滑块的plotly来创建一个choropleth地图,然而,虽然我可以让地图输出,但我在尝试添加滑块时收到了以下错误。我仔细检查了代码,并将其与我一直遵循的tutorial进行了比较--然而,我使用的是不同的data set。
错误:
/opt/conda/lib/python3.7/site-packages/ipykernel_launcher.py:15: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
/tmp/ipykernel_43/4083138113.py in <module>
44
45 fig = dict(data=data_slider, layout=layout)
---> 46 plotly.offline.iplot(fig)
/opt/conda/lib/python3.7/site-packages/plotly/offline/offline.py in iplot(figure_or_data, show_link, link_text, validate, image, filename, image_width, image_height, config, auto_play, animation_opts)
382
383 # Get figure
--> 384 figure = tools.return_figure_from_figure_or_data(figure_or_data, validate)
385
386 # Handle image request
/opt/conda/lib/python3.7/site-packages/plotly/tools.py in return_figure_from_figure_or_data(figure_or_data, validate_figure)
551
552 try:
--> 553 figure = Figure(**figure).to_dict()
554 except exceptions.PlotlyError as err:
555 raise exceptions.PlotlyError(
/opt/conda/lib/python3.7/site-packages/plotly/graph_objs/_figure.py in __init__(self, data, layout, frames, skip_invalid, **kwargs)
588 is invalid AND skip_invalid is False
589 """
--> 590 super(Figure, self).__init__(data, layout, frames, skip_invalid, **kwargs)
591
592 def add_bar(
/opt/conda/lib/python3.7/site-packages/plotly/basedatatypes.py in __init__(self, data, layout_plotly, frames, skip_invalid, **kwargs)
558 # ### Import Layout ###
559 self._layout_obj = self._layout_validator.validate_coerce(
--> 560 layout, skip_invalid=skip_invalid, _validate=self._validate
561 )
562
/opt/conda/lib/python3.7/site-packages/_plotly_utils/basevalidators.py in validate_coerce(self, v, skip_invalid, _validate)
2465
2466 elif isinstance(v, dict):
-> 2467 v = self.data_class(v, skip_invalid=skip_invalid, _validate=_validate)
2468
2469 elif isinstance(v, self.data_class):
/opt/conda/lib/python3.7/site-packages/plotly/graph_objs/_layout.py in __init__(self, arg, activeshape, annotations, annotationdefaults, autosize, autotypenumbers, bargap, bargroupgap, barmode, barnorm, boxgap, boxgroupgap, boxmode, calendar, clickmode, coloraxis, colorscale, colorway, computed, datarevision, dragmode, editrevision, extendfunnelareacolors, extendiciclecolors, extendpiecolors, extendsunburstcolors, extendtreemapcolors, font, funnelareacolorway, funnelgap, funnelgroupgap, funnelmode, geo, grid, height, hiddenlabels, hiddenlabelssrc, hidesources, hoverdistance, hoverlabel, hovermode, iciclecolorway, images, imagedefaults, legend, mapbox, margin, meta, metasrc, modebar, newshape, paper_bgcolor, piecolorway, plot_bgcolor, polar, scene, selectdirection, selectionrevision, separators, shapes, shapedefaults, showlegend, sliders, sliderdefaults, spikedistance, sunburstcolorway, template, ternary, title, titlefont, transition, treemapcolorway, uirevision, uniformtext, updatemenus, updatemenudefaults, violingap, violingroupgap, violinmode, waterfallgap, waterfallgroupgap, waterfallmode, width, xaxis, yaxis, **kwargs)
6012 _v = geo if geo is not None else _v
6013 if _v is not None:
-> 6014 self["geo"] = _v
6015 _v = arg.pop("grid", None)
6016 _v = grid if grid is not None else _v
/opt/conda/lib/python3.7/site-packages/plotly/basedatatypes.py in __setitem__(self, prop, value)
5819 if match is None:
5820 # Set as ordinary property
-> 5821 super(BaseLayoutHierarchyType, self).__setitem__(prop, value)
5822 else:
5823 # Set as subplotid property
/opt/conda/lib/python3.7/site-packages/plotly/basedatatypes.py in __setitem__(self, prop, value)
4809 # ### Handle compound property ###
4810 if isinstance(validator, CompoundValidator):
-> 4811 self._set_compound_prop(prop, value)
4812
4813 # ### Handle compound array property ###
/opt/conda/lib/python3.7/site-packages/plotly/basedatatypes.py in _set_compound_prop(self, prop, val)
5220 # ------------
5221 validator = self._get_validator(prop)
-> 5222 val = validator.validate_coerce(val, skip_invalid=self._skip_invalid)
5223
5224 # Save deep copies of current and new states
/opt/conda/lib/python3.7/site-packages/_plotly_utils/basevalidators.py in validate_coerce(self, v, skip_invalid, _validate)
2465
2466 elif isinstance(v, dict):
-> 2467 v = self.data_class(v, skip_invalid=skip_invalid, _validate=_validate)
2468
2469 elif isinstance(v, self.data_class):
/opt/conda/lib/python3.7/site-packages/plotly/graph_objs/layout/_geo.py in __init__(self, arg, bgcolor, center, coastlinecolor, coastlinewidth, countrycolor, countrywidth, domain, fitbounds, framecolor, framewidth, lakecolor, landcolor, lataxis, lonaxis, oceancolor, projection, resolution, rivercolor, riverwidth, scope, showcoastlines, showcountries, showframe, showlakes, showland, showocean, showrivers, showsubunits, subunitcolor, subunitwidth, uirevision, visible, **kwargs)
1560 # Process unknown kwargs
1561 # ----------------------
-> 1562 self._process_kwargs(**dict(arg, **kwargs))
1563
1564 # Reset skip_invalid
/opt/conda/lib/python3.7/site-packages/plotly/basedatatypes.py in _process_kwargs(self, **kwargs)
4335 self[k] = v
4336 elif not self._skip_invalid:
-> 4337 raise err
4338 # No need to call _raise_on_invalid_property_error here,
4339 # because we have it set up so that the singular case of calling
ValueError: Invalid property specified for object of type plotly.graph_objs.layout.Geo: 'sliders'
Did you mean "center"?
Bad property path:
sliders
^^^^^^^代码
import plotly.graph_objs as go
import plotly
import plotly.graph_objs as go
import plotly.offline as offline
import time
import plotly.express as px
fig = px.choropleth(df_total, locations="Code",
color="Total Deaths", # lifeExp is a column of gapminder
hover_name="Entity", # column to add to hover information
color_continuous_scale=px.colors.sequential.Plasma)
fig.update_layout(
autosize=False,
width=1000,
height=800,)
fig.show()

#Slider
#color scale
scl = [[0.0, '#ffffff'],[0.2, '#ff9999'],[0.4, '#ff4d4d'], \
[0.6, '#ff1a1a'],[0.8, '#cc0000'],[1.0, '#4d0000']]
# min year in your dataset
year = 1990
data_slider = []
for year in df_total['Year'].unique():
df_segmented = df_total[(df_total['Year']== year)]
for col in df_segmented.columns:
df_segmented[col] = df_segmented[col].astype(str)
data_each_yr = dict(
type='choropleth',
locations = df_segmented['Entity'],
z=df_segmented['Total Deaths'].astype(float),
locationmode= 'country names',
colorscale = scl,
colorbar= {'title':'# Deaths - Total Air pollution Deaths'})
data_slider.append(data_each_yr)
steps = []
for i in range(len(data_slider)):
step = dict(method='restyle',
args=['visible', [False] * len(data_slider)],
label='Year {}'.format(i + 1990))
step['args'][1][i] = True
steps.append(step)
sliders = [dict(active=0, pad={"t": 1}, steps=steps)]
layout = dict(title ='Global Air Pollution Deaths 1990-2020', geo=dict(
showframe=False,
showcoastlines=False,
projection_type='equirectangular',
sliders=sliders))
fig = dict(data=data_slider, layout=layout)
plotly.offline.iplot(fig)发布于 2021-10-05 03:48:48
错误是由于写入有条件提取的数据帧造成的,因此将提取结果放入临时数据帧中,并将其添加到最终形式的数据帧中。
df_sected_crime = pd.DataFrame()
for year in df_merged.Year.unique():
# I select the year (and remove DC for now)
tmp = df_merged[(df_merged['State'] != 'District of Columbia' ) & (df_merged['Year']== year )]
tmp2 = tmp.copy()
#for col in df_sected_crime.columns: # I transform the columns into string type so I can:
#df_sected_crime[col] = df_sected_crime[col].astype(str)
### I create the text for mouse-hover for each state, for the current year
tmp2['text'] = tmp2['State'] + '</br>Pop: ' + tmp2['Population'].astype(str) + '</br>Murder rate: '+ tmp2['Murder_per100000'].astype(str)
df_sected_crime = df_sected_crime.append(tmp2)
### create the dictionary with the data for the current year
data_one_year = dict(
type='choropleth',
locations = df_sected_crime['State_code'],
z=df_sected_crime['Murder_per100000'].astype(float),
locationmode='USA-states',
colorscale = scl,
text = df_sected_crime['text'],
)
data_slider.append(data_one_year) # I add the dictionary to the list of dictionaries for the slider

https://stackoverflow.com/questions/69441864
复制相似问题