我已经创建了一个Choropleth地图,我想知道是否可以为每个州添加一个下拉列表。当您选择下拉列表时,图表会更改为该州内一段时间内获得的学士学位数的折线图。
我的数据样本:
year state statetotal ba_total
0 1984.0 AK 221.0 108.0
1 1985.0 AK 242.0 141.0
2 1984.0 NC 229.0 117.0
3 1985.0 NC 257.0 138.0
4 1984.0 MA 272.0 165.0
5 1985.0 MA 280.0 176.0
6 1984.0 NY 375.0 249.0
7 1985.0 NY 309.0 208.0
这是我迄今为止所尝试过的:
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['statename'] + '<br>' + \
'Bachelor '+df['ba_total']+'<br>'+ \
'Master '+df['ma_total']+'<br>'+ \
'PhD '+df['phd_total']
# Years
years = list(df['year'].astype(float).astype(int).unique())
# make data
data = []
# Append data
for year in years:
dataset_by_year = df[df['year'].astype(float).astype(int) == int(year)]
data_dict = [ dict(
type='choropleth',
visible=True,
colorscale = scl,
autocolorscale = False,
locations = dataset_by_year['state'],
z = dataset_by_year['statetotal'].astype(float),
locationmode = 'USA-states',
text = dataset_by_year['text'],
marker = dict(
line = dict (
color = 'rgb(255,255,255)',
width = 2
) ),
colorbar = dict(
title = "Educ. Grads")
) ]
data.append(data_dict[0])
# let's create the steps for the slider
steps = []
for i in range(len(data)):
step = dict(method='restyle',
args=['visible', [False] * len(data)],
label='{}'.format(i + 1984))
step['args'][1][i] = True
steps.append(step)
sliders = [dict(active=0,
pad={"t": 1},
steps=steps)]
# create the empty dropdown menu
updatemenus = list([dict(buttons=list()),
dict(direction='down',
showactive=True)])
total_codes = len(df.state.unique()) + 1
for s, state in enumerate(df.state.unique()):
# add a trace for each state
data.append(dict(type='scatter',
x=[i for i in range(1984, 2016)],
y=[i for i in df.statetotal],
visible=False))
# add each state to the dropdown
visible_traces = [False] * total_codes
visible_traces[s + 1] = True
updatemenus[0]['buttons'].append(dict(args=[{'visible': visible_traces}],
label=state,
method='update'))
# add a dropdown entry to reset the map
updatemenus[0]['buttons'].append(dict(args=[{'visible': [True] + [False] * (total_codes - 1)}],
label='Map',
method='update'))
layout = dict(title='Aggregated Number of Graduates in Education by State',
updatemenus=updatemenus,
geo=dict(scope='usa',
projection={'type': 'albers usa'}),
sliders=sliders)
fig = dict(data=data,
layout=layout)
我得到的AttributeError
与我创建的功能有关,但之前我设法生成带有菜单的图表,但图表生成了50个菜单按钮,而不是下拉菜单50个选项。
我认为这些问题可以解决,但问题的关键在于是否可以将图表类型组合在一起?理想情况下,如果我点击阿拉斯加州,显示在所观察的时间段内完成的单身汉学位数,我想要显示折线图。 这可能吗?
编辑代码
我设法让下拉菜单工作,但它与slider和地图没有很好地融合。当您点击下拉菜单中的项目或如何防止地图重叠在折线图顶部时,我不知道如何让滑块消失。
答案 0 :(得分:3)
您可以使用Plotly在线获得所需的功能,但在渲染第一个图形时需要加载所有数据。也许看看Plotly的Dash,它可以动态加载数据。
为了获得显示痕迹的dropmenu,您可以执行以下操作:
visible
属性来显示地图。visible
)import pandas as pd
import plotly
plotly.offline.init_notebook_mode()
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv')
# create the initial map
data = [dict(type='choropleth',
locations = df['code'].astype(str),
z=df['total exports'].astype(float),
locationmode='USA-states',
visible=True)]
layout = dict(geo=dict(scope='usa',
projection={'type': 'albers usa'}))
# create the empty dropdown menu
updatemenus = list([dict(buttons=list()),
dict(direction='down',
showactive=True)])
total_codes = len(df.code.unique()) + 1
for s, state in enumerate(df.code.unique()):
# add a trace for each state
data.append(dict(type='scatter',
x=[i for i in range(1980, 2016)],
y=[i + random.random() * 100 for i in range(1980, 2016)],
visible=False))
# add each state to the dropdown
visible_traces = [False] * total_codes
visible_traces[s + 1] = True
updatemenus[0]['buttons'].append(dict(args=[{'visible': visible_traces}],
label=state,
method='update'))
# add a dropdown entry to reset the map
updatemenus[0]['buttons'].append(dict(args=[{'visible': [True] + [False] * (total_codes - 1)}],
label='Map',
method='update'))
layout['updatemenus'] = updatemenus
fig = dict(data=data,
layout=layout)
plotly.offline.iplot(fig)