Python 绘图错误

标签 python plotly mapping

plotly 网站上的 choropleth map 示例代码似乎已过时且不再有效。

我收到的错误是:

PlotlyError: Invalid 'figure_or_data' argument. Plotly will not be able to properly parse the resulting JSON. If you want to send this 'figure_or_data' to Plotly anyway (not recommended), you can set 'validate=False' as a plot option.
Here's why you're seeing this error:

The entry at index, '0', is invalid because it does not contain a valid 'type' key-value. This is required for valid 'Data' lists.

Path To Error:
['data'][0]

我尝试运行的代码如下所示。它是从plotly 网站上按原样复制的。有人对如何修复它有任何想法吗?

import plotly.plotly as py
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)

url = py.plot(fig, filename='d3-cloropleth-map')

最佳答案

fig 应该是 Figure 类型。使用 Choropleth 图形对象:

import plotly.graph_objs as go
...
data = [go.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")
        )]

...
fig = go.Figure(data=data, layout=layout)
...

关于Python 绘图错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48189304/

相关文章:

python - 如何使用 QAbstractTableModel 模型控制其他小部件?

python - scrapyd 中的类型错误

python - cPickle.dump 总是在文件末尾转储

pandas - 将绘图保存在一个 pdf 文件中

python - 绘图中 x 轴上的时间

java - 当 url 有参数时,JSF 不会呈现

vim - 如何使 Vim 插件 NERDTree 的 <CR> 表现得更像 `go` ?

Python:将列表写入xml文件

javascript - plotly.js - 如何修复条形图中条形之间的空间

c++ - 如何将 3D 点云转换为深度图像?