2.1.9.1.Choropleth Maps - USA

1. 使用library

import plotly.plotly as py
import plotly.graph_objs as go 
from plotly.offline import download_plotlyjs,init_notebook_mode,plot,iplot
init_notebook_mode(connected = True)

2.基本操作

  • Choropleth Map的兩個要素:

    • Data

      • 指定locationmode = 'USA-states'

        data = dict(type = 'choropleth', 
          locations = ['AZ', 'CA', 'NY'], 
          locationmode = 'USA-states', 
          colorscale = 'Portland', 
          text = ['Arizona', 'Cali', 'New York'], 
          z = [1.0 , 2.0, 3.0], 
          colorbar = {'title': 'colorbar title goes here'})
    • Layout

      • 在geo中指定'scope': 'usa'

        layout = dict(geo={'scope': 'usa'})
  • 製作Choropleth Map

choromap = go.Figure(data = [data], layout = layout)
iplot(choromap)

3.從實際資料中繪製Choropleth Map

  • 讀取資料

    • 可在資料中放入想要顯示的country code, z值 (數量), label

      import pandas as pd
      df = pd.read_csv('2011_US_AGRI_Exports')
      df.head()
  • Choropleth Map的兩個要素 Data, Layout

    data = dict(type = 'choropleth',
           colorscale = 'YIOrRd',
           locations = df['code'],
           locationmode = 'USA-states',
           z = df['total exports'],
           text = df['text'],
           marker = dict(line = dict(color = 'rgb(255, 255, 255)', width = 2)), 
           colorbar = {'title': 'Millions USD'})
   layout = dict(title = '2011 US Agiculture Exports bt states', 
              geo = dict(scope = 'usa', showlakes = True, lakecolor = 'rgb(85, 173, 240)'))
  • 製作Choropleth Map

choromap2 = go.Figure(data = [data], layout = layout)
iplot(choromap2)

Last updated