Plotly官网Choropleth地图示例代码失效,报PlotlyError求助修复
修复Plotly Choropleth地图的
Invalid 'figure_or_data'错误 问题原因
嘿,我之前也碰到过一模一样的问题!这个报错其实是因为你用了已被官方弃用的Plotly云端API模块plotly.plotly。这个模块是早期Plotly用来上传图表到云端的工具,现在Plotly已经全面转向本地渲染的架构,旧模块的解析逻辑和新版Figure结构不兼容,才会误报“缺少'type'键”的错误——实际上你的数据结构完全没问题,只是API版本不对而已。
修复步骤
1. 替换导入模块
把旧的云端API导入换成本地渲染的plotly.graph_objects(如果想更简洁也可以用plotly.express,这里贴合原代码结构用graph_objects):
# 替换前 import plotly.plotly as py # 替换后 import plotly.graph_objects as go
2. 修改图表渲染方式
原代码的py.plot()是上传到Plotly云端的方法,现在改成本地直接显示的fig.show():
# 替换前 url = py.plot(fig, filename='d3-cloropleth-map') # 替换后 fig.show()
3. 优化文本格式(可选)
原代码里的<br>是HTML转义字符,新版Plotly支持直接用<br>换行,可读性会更好:
df['text'] = df['state'] + '<br>' +\ 'Beef '+df['beef']+' Dairy '+df['dairy']+'<br>'+ 'Fruits '+df['total fruits']+' Veggies ' + df['total veggies']+'<br>'+ 'Wheat '+df['wheat']+' Corn '+df['corn']
完整修复后代码
import plotly.graph_objects as go import pandas as pd df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv') for col in df.columns: df[col] = df[col].astype(str) scl = [[0.0, 'rgb(242,240,247)'],[0.2, 'rgb(218,218,235)'],[0.4, 'rgb(188,189,220)'], [0.6, 'rgb(158,154,200)'],[0.8, 'rgb(117,107,177)'],[1.0, 'rgb(84,39,143)']] df['text'] = df['state'] + '<br>' +\ 'Beef '+df['beef']+' Dairy '+df['dairy']+'<br>'+ 'Fruits '+df['total fruits']+' Veggies ' + df['total veggies']+'<br>'+ 'Wheat '+df['wheat']+' Corn '+df['corn'] data = [ dict( type='choropleth', colorscale = scl, autocolorscale = False, locations = df['code'], z = df['total exports'].astype(float), locationmode = 'USA-states', text = df['text'], marker = dict( line = dict ( color = 'rgb(255,255,255)', width = 2 ) ), colorbar = dict( title = "Millions USD" ) ) ] layout = dict( title = '2011 US Agriculture Exports by State<br>(Hover for breakdown)', geo = dict( scope='usa', projection=dict( type='albers usa' ), showlakes = True, lakecolor = 'rgb(255, 255, 255)', ), ) fig = dict(data=data, layout=layout) fig.show()
额外说明
如果之后你确实需要把图表分享到云端,可以用plotly.io.write_html()保存为本地HTML文件,或者登录Plotly账号使用新版云端上传工具,但日常使用本地渲染的fig.show()完全能满足需求啦。
内容的提问来源于stack exchange,提问作者Cameron
相关产品推荐
相关产品推荐

