📜  如何在Python中使用 Plotly 制作带有滑块的等值线图?

📅  最后修改于: 2022-05-13 01:55:07.498000             🧑  作者: Mango

如何在Python中使用 Plotly 制作带有滑块的等值线图?

Choropleth Map是一种专题地图,其中一组预定义的区域按照代表每个区域内地理特征的汇总摘要的统计变量按比例着色或图案化。 Choropleth 地图提供了一种简单的方法来可视化变量在地理区域内的变化或显示区域内的可变性水平。

滑块可用于 plotly 更改显示的数据或绘图的样式。这是一个方便的工具,可用于显示等值线图的变化。

安装

让我们从安装 plotly 开始:

pip install plotly

现在,让我们导入必要的库。

Python3
import pandas as pd
import plotly
import numpy as np


Python3
df = pd.read_csv('https://raw.githubusercontent\
.com/plotly/datasets/master/2011_us_ag_exports.csv')
  
data = [dict(type='choropleth', 
            locations = df['code'].astype(str),
            z=df['total exports'].astype(float),
            locationmode='USA-states')]


Python3
steps = []
  
for i in range(len(data)):
    step = dict(method='restyle',
                args=['visible', [False] * len(data)],
                label='Year {}'.format(i + 1980))
    step['args'][1][i] = True
    steps.append(step)
  
sliders = [dict(active=0, pad={"t": 1}, steps=steps)]


Python3
import pandas as pd
import plotly
import numpy as np
  
plotly.offline.init_notebook_mode()
  
# Reading sample data using pandas DataFrame
df = pd.read_csv('https://raw.githubusercontent.\
com/plotly/datasets/master/2011_us_ag_exports.csv')
  
data = [dict(type='choropleth',
             locations = df['code'].astype(str),
             z=df['total exports'].astype(float),
             locationmode='USA-states')]
  
# let's create some more additional, data
for i in range(5):
    data.append(data[0].copy())
    data[-1]['z'] = data[0]['z'] * np.random.rand(*data[0]['z'].shape)
  
# let's now create slider for map
steps = []
for i in range(len(data)):
    step = dict(method='restyle',
                args=['visible', [False] * len(data)],
                label='Year {}'.format(i + 1980))
    step['args'][1][i] = True
    steps.append(step)
  
slider = [dict(active=0,
                pad={"t": 1},
                steps=steps)]    
layout = dict(geo=dict(scope='usa',
                       projection={'type': 'albers usa'}),
              sliders=slider)
  
fig = dict(data=data, 
           layout=layout)
plotly.offline.iplot(fig)


加载数据集

加载样本数据集。我们将使用此数据集绘制等值线图。

Python3

df = pd.read_csv('https://raw.githubusercontent\
.com/plotly/datasets/master/2011_us_ag_exports.csv')
  
data = [dict(type='choropleth', 
            locations = df['code'].astype(str),
            z=df['total exports'].astype(float),
            locationmode='USA-states')]

创建滑块

现在,让我们构建我们的滑块

Python3

steps = []
  
for i in range(len(data)):
    step = dict(method='restyle',
                args=['visible', [False] * len(data)],
                label='Year {}'.format(i + 1980))
    step['args'][1][i] = True
    steps.append(step)
  
sliders = [dict(active=0, pad={"t": 1}, steps=steps)]

带输出的最终代码

最后,让我们将所有代码放在一起,用滑块绘制等值线图。

Python3

import pandas as pd
import plotly
import numpy as np
  
plotly.offline.init_notebook_mode()
  
# Reading sample data using pandas DataFrame
df = pd.read_csv('https://raw.githubusercontent.\
com/plotly/datasets/master/2011_us_ag_exports.csv')
  
data = [dict(type='choropleth',
             locations = df['code'].astype(str),
             z=df['total exports'].astype(float),
             locationmode='USA-states')]
  
# let's create some more additional, data
for i in range(5):
    data.append(data[0].copy())
    data[-1]['z'] = data[0]['z'] * np.random.rand(*data[0]['z'].shape)
  
# let's now create slider for map
steps = []
for i in range(len(data)):
    step = dict(method='restyle',
                args=['visible', [False] * len(data)],
                label='Year {}'.format(i + 1980))
    step['args'][1][i] = True
    steps.append(step)
  
slider = [dict(active=0,
                pad={"t": 1},
                steps=steps)]    
layout = dict(geo=dict(scope='usa',
                       projection={'type': 'albers usa'}),
              sliders=slider)
  
fig = dict(data=data, 
           layout=layout)
plotly.offline.iplot(fig)

输出: