python - 在 python 中离线绘制世界 Choropleth map ?

标签 python pandas plotly visualization choropleth

我正在尝试重新创建 plotlys 示例页面中给出的世界 Choropleth map :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')

enter image description here

这会在 jupyter notebook 中内联渲染图像,并且有一个按钮允许您在右上角将绘图下载为 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.

关于python - 在 python 中离线绘制世界 Choropleth map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52990452/

相关文章:

python - 如何在python中提取txt文件中的数字

python - 使用 pandas 根据键变量将多行转换为单行

python - 使用 pathlib 时,出现错误 : TypeError: invalid file: PosixPath ('example.txt' )

python - 如何绘制列中的某些值(子图)

python - 使用按钮在 Plotly 中绘制工厂热图

python - 如何在 plotly express 中更改散点矩阵中的轴限制?

python - Pyhook 事件。注入(inject)?

python - Pandas :在数据框中重新分配值

python - 将文本转换为二进制列

python - 如何在没有输入的情况下使用破折号回调