在 python 中离线绘制世界 Choropleth 地图?

Plotly world Choropleth Map offline in python?

我正在尝试重新创建 plotlys 示例页面中给出的世界 Choropleth 地图:https://plot.ly/python/choropleth-maps/ 目的是重用一些代码,但更改通知阴影和标签的列。

然而,当我 运行 示例中给出的确切代码时,我收到以下错误。

plotly.exceptions.PlotlyError: Because you didn't supply a 'file_id' in the call, we're assuming you're trying to snag a figure from a url. You supplied the url, '', we expected it to start with 'https://plot.ly'. Run help on this function for more information.

我不知道这个错误是从哪里产生的,我的问题是如何调整代码以便离线生成上述图形?其次,有没有一种简单的方法可以将图形直接保存为 png?抱歉,如果这是微不足道的,我是这个包的新手。

代码如下:

import plotly.plotly as py
import pandas as pd

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv')
data = [dict(
    type='choropleth',
    locations=df['CODE'],
    z=df['GDP (BILLIONS)'],
    text=df['COUNTRY'],
    colorscale=[[0, "rgb(5, 10, 172)"], [0.35, "rgb(40, 60, 190)"], [0.5, "rgb(70, 100, 245)"],\
                [0.6, "rgb(90, 120, 245)"], [0.7, "rgb(106, 137, 247)"], [1, "rgb(220, 220, 220)"]],
    autocolorscale=False,
    reversescale=True,
    marker=dict(
        line=dict(
            color='rgb(180,180,180)',
            width=0.5
        )),
    colorbar=dict(
        autotick=False,
        tickprefix='$',
        title='GDP<br>Billions US$'),
)]

layout = dict(
    title='2014 Global GDP<br>Source:\
            <a href="https://www.cia.gov/library/publications/the-world-factbook/fields/2195.html">\
            CIA World Factbook</a>',
    geo=dict(
        showframe=False,
        showcoastlines=False,
        projection=dict(
            type='Mercator'
        )
    )
)

fig = dict(data=data, layout=layout)
py.iplot(fig,validate=False, filename='d3-world-map')

您需要导入离线特定函数,它允许您在 jupyter notebook 中内联绘图:

import plotly.figure_factory as ff
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)

# All of your code
# ....

# Just change the last line from py.iplot to iplot
iplot(fig,validate=False, filename='d3-world-map')

这会在 jupyter notebook 中内联呈现图像,右上角有一个按钮,可让您 Download plot as a png 以及其他功能。


如果需要将图片另存为png格式,可以尝试将最后一行改为:

plot(fig, validate=False, filename='d3-world-map.html', image='png')

这实际上会创建一个 .html 文件并将打开浏览器。然后您可以手动将其另存为 .png。最后一步可以通过 selenium 等其他库自动执行,但鉴于它们的 documentation:

,不确定是否有简单的解决方法

Note that you must generate the graph and open the file to save the image.