> For the complete documentation index, see [llms.txt](https://jen-hsuan-hsieh.gitbook.io/python/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jen-hsuan-hsieh.gitbook.io/python/chapter-2courses/21python-for-data-science-and-machine-learning-bootcamp/dsad/2191chropleth-maps-usa.md).

# 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)
```

![](https://1184108162-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M4M0G8SFgkeUaGo4vl-%2F-M4M0HrDfjWeZX2tGCNv%2F-M4M0Rl7ggwJjKKbV8TK%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-06-02%20%E4%B8%8B%E5%8D%883.46.11.png?generation=1586302953553461\&alt=media)

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

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

    ```
    import pandas as pd
    df = pd.read_csv('2011_US_AGRI_Exports')
    df.head()
    ```

    ![](https://1184108162-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M4M0G8SFgkeUaGo4vl-%2F-M4M0HrDfjWeZX2tGCNv%2F-M4M0Rl9-LWqQ866s0I6%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-06-02%20%E4%B8%8B%E5%8D%883.49.34.png?generation=1586302953322663\&alt=media)
* 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)
```

![](https://1184108162-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M4M0G8SFgkeUaGo4vl-%2F-M4M0HrDfjWeZX2tGCNv%2F-M4M0RlBvokgRKqZQO_K%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-06-02%20%E4%B8%8B%E5%8D%883.59.11.png?generation=1586302953273791\&alt=media)
