2017-10-16 18 views
1

example choropleth을 다시 만들고 드래그 할 때 해마다 바뀔 슬라이더를 추가하려고합니다. 다른 사용자가 similar question에게 질문했지만 회신을받지 못했습니다. 좀 더 검색을하고 example을 발견했습니다. 사용자가 추가 연도에 임의의 값을 생성하고 슬라이더를 만들었지 만 자바 스크립트로 작성되었으며 파이썬으로 변환하는 방법을 모르겠습니다.Plotly를 사용하여 슬라이더로 choropleth 맵을 만드는 방법은 무엇입니까?

Plotly.d3.csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv', function(err, rows){ 
    function unpack(rows, key) { 
    return rows.map(function(row) { return row[key]; }); 
    } 

    var randomize = z => z.map(d => Math.pow(Math.random(), 2) * 30000); 
    var data = unpack(rows, 'total exports'); 
    var frames = [{ 
    data: [{z: unpack(rows, 'total exports')}], 
    traces: [0], 
    name: '1990', 
    layout: {title: '1990 US Agriculture Exports by State'} 
    }, { 
    data: [{z: randomize(data)}], 
    traces: [0], 
    name: '1995', 
    layout: {title: '1995 US Agriculture Exports by State'} 
    }, { 
    data: [{z: randomize(data)}], 
    traces: [0], 
    name: '2000', 
    layout: {title: '2000 US Agriculture Exports by State'} 
    }, { 
    data: [{z: randomize(data)}], 
    traces: [0], 
    name: '2005', 
    layout: {title: '2005 US Agriculture Exports by State'} 
    }] 

    var data = [{ 
    type: 'choropleth', 
    locationmode: 'USA-states', 
    locations: unpack(rows, 'code'), 
    z: unpack(rows, 'total exports'), 
    text: unpack(rows, 'state'), 
    zmin: 0, 
    zmax: 17000, 
    colorscale: [ 
     [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, 'rgb(84,39,143)'] 
    ], 
    colorbar: { 
     title: 'Millions USD', 
     thickness: 0.2 
    }, 
    marker: { 
     line:{ 
     color: 'rgb(255,255,255)', 
     width: 2 
     } 
    } 
    }]; 


    var layout = { 
    title: '1990 US Agriculture Exports by State', 
    geo:{ 
     scope: 'usa', 
     showlakes: true, 
     lakecolor: 'rgb(255,255,255)' 
    }, 
    xaxis: {autorange: false}, 
    yaxis: {autorange: false}, 
    sliders: [{ 
     currentvalue: { 
     prefix: 'Year: ', 
     }, 
     steps: frames.map(f => ({ 
     label: f.name, 
     method: 'animate', 
     args: [[f.name], {frame: {duration: 0}}] 
     })) 
    }] 
    }; 

    Plotly.plot('graph', { 
    data: data, 
    layout: layout, 
    frames: frames, 
    config: {showLink: false} 
    }); 
}); 

파이썬이 할 수있는 방법이 있나요 :

여기에 자바 스크립트의 코드는?

답변

5

아래 코드는 실질적으로 파이썬 용 과 sliders 코드의 줄임말입니다.

첫 번째 데이터를 기준으로 무작위 데이터가 생성되고 각 슬라이더 항목은 데이터 목록의 다른 부분을 표시합니다.

import pandas as pd 
import plotly 
import numpy as np 

plotly.offline.init_notebook_mode() 
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 additional, random 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 create the steps for the slider 
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)]  
layout = dict(geo=dict(scope='usa', 
         projection={'type': 'albers usa'}), 
       sliders=sliders) 

fig = dict(data=data, 
      layout=layout) 
plotly.offline.iplot(fig) 

enter image description here

+0

이는 위대하다! 고맙습니다. 하나의 작은 화장 용 질문. "step-0"대신 "Year : 1980"라고 말하고 1990 년까지 단계별로 표시하려면 어떻게합니까? – otteheng

+0

'단계''dict'에'label = 'Year {}'. format (i + 1980)'를 추가하십시오. 업데이트 된 답변을 참조하십시오. –

+0

이것은 작동합니다. 코드에서 하나의 작은 오류가 발생했습니다. 대괄호는'args = [ 'visible', [False] * len (data)]'를 감싸 야합니다. – otteheng