# 2.1.9.2.Choropleth Maps - World

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

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

      ```
      import pandas as pd
      df = pd.read_csv('2014_World_GDP')
      df.head()
      ```

      ![](https://1184108162-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M4M0G8SFgkeUaGo4vl-%2F-M4M0HrDfjWeZX2tGCNv%2F-M4M0SoXopAfx35v8csP%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-06-02%20%E4%B8%8B%E5%8D%884.14.13.png?generation=1586302954689085\&alt=media)
* Choropleth Map的兩個要素 Data, Layout
  *   Data的locationmode預設為country code, 因此若locations是country code則不需指定locationmode

      ```
      data = dict(
        type = 'choropleth',
        locations = df['CODE'],
        z = df['GDP (BILLIONS)'],
        text = df['COUNTRY'],
        colorbar = {'title' : 'GDP Billions US'},
      ) 

      layout = dict(
      title = '2014 Global GDP',
      geo = dict(
        showframe = False,
        projection = {'type':'Mercator'}
      )
      )
      ```
  *   若資料來源是country name, 則必須在指定locationmode中指定: locationmode = "country names"

      ```
      data = dict(
        type = 'choropleth',
        locations = df['COUNTRY'],
        locationmode = "country names",
        z = df['GDP (BILLIONS)'],
        text = df['COUNTRY'],
        colorbar = {'title' : 'GDP Billions US'},
      )

      layout = dict(
      title = '2014 Global GDP',
      geo = dict(
        showframe = False,
        projection = {'type':'Mercator'}
      )
      )
      ```
* 製作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-M4M0So_cEUUXcxL9T_i%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-06-02%20%E4%B8%8B%E5%8D%884.16.23.png?generation=1586302954575495\&alt=media)
