Powered by AppSignal & Oban Pro

USA Choropleth Map

10_usa_choropleth_map.livemd

USA Choropleth Map

Mix.install([
  {:plotly_ex, "~> 0.3"},
  {:kino, "~> 0.18"},
  {:req, "~> 0.5"}
])

Section

For US state choropleth, use locationmode: "USA-states" with 2-letter state codes. geo.scope: "usa" zooms to the US. Fetch real state data from Plotly's dataset repo.

alias Plotly.{Figure, Choropleth}

url = "https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv"
body = Req.get!(url).body

[header | rows] = String.split(body, "\n", trim: true)
keys = String.split(header, ",") |> Enum.map(&String.trim/1)

data =
  rows
  |> Enum.map(fn row ->
    values = String.split(row, ",")
    Enum.zip(keys, values) |> Map.new()
  end)

states = Enum.map(data, & &1["code"])
values = Enum.map(data, &(elem(Float.parse(&1["total exports"]), 0)))
text = Enum.map(data, fn r -> "#{r["state"]}<br>Exports: $#{r["total exports"]}M" end)

Figure.new()
|> Figure.add_trace(
  Choropleth.new(
    locations: states,
    z: values,
    text: text,
    locationmode: "USA-states",
    colorscale: "Greens",
    colorbar: %{title: %{text: "$ Millions"}},
    marker: %{line: %{color: "white", width: 1}}
  )
)
|> Figure.update_layout(
  title: "USA Agricultural Exports — 2011",
  geo: %{
    scope: "usa",
    showland: true,
    landcolor: "#EAEAAE",
    showlakes: true,
    lakecolor: "#BDDDE4"
  }
)
|> Plotly.show()