# How Do I Add a Colorbar to a Choropleth Map?

**URL:** https://discourse.julialang.org/t/how-do-i-add-a-colorbar-to-a-choropleth-map/57814
**Category:** General Usage
**Tags:** plotting, data, shapes, shapefile
**Created:** [March 23, 2021, 6:31pm UTC](https://discourse.julialang.org/t/how-do-i-add-a-colorbar-to-a-choropleth-map/57814 "2021-03-23T18:31:40Z")
**Posts on this page:** 6
**Page:** 1

<div class="post-metadata">

### Author: ![TheCedarPrince](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/thecedarprince/32/17323_2.png) [@TheCedarPrince](https://discourse.julialang.org/u/TheCedarPrince)
#### Post date: [March 23, 2021, 6:31pm UTC](https://discourse.julialang.org/t/how-do-i-add-a-colorbar-to-a-choropleth-map/57814/1 "2021-03-23T18:31:40Z")

</div>

Hi all,

I have a choropleth plot that I have made using the following code snippet:

```julia
choropleth = plot(states.geometry, axis = ([], false); fillcolor = permutedims(random_values))

```

It comes out looking like this:

![image](https://global.discourse-cdn.com/julialang/original/3X/0/5/059bfa7a7bbea5c71ff6809f8f9f64e4fff038e8.png)

How do I add a colorbar to this graphic?

I saw this stack exchange post from a couple months ago so I see that it is still an open question: [dataframe - How to add a colorbar to a thematic map plot in Julia? - Stack Overflow](https://stackoverflow.com/questions/65207452/how-to-add-a-colorbar-to-a-thematic-map-plot-in-julia)

Thanks all!

~ tcp 🌳

---

<div class="post-metadata">

### Author: ![lungd](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lungd/32/10913_2.png) [@lungd](https://discourse.julialang.org/u/lungd)
#### Post date: [March 23, 2021, 8:02pm UTC](https://discourse.julialang.org/t/how-do-i-add-a-colorbar-to-a-choropleth-map/57814/2 "2021-03-23T20:02:00Z")

</div>

Maybe you can make use of the KW fill\_z

```julia
using DataFrames
using Plots
using Shapefile
using ZipFile

# make directory downloads
downloads = joinpath(pwd(), "downloads")
if ~ispath(downloads)
    mkpath(downloads)
end

# make directory shapefiles
shapefiles = joinpath(pwd(), "shapefiles")
if ~ispath(shapefiles)
    mkpath(shapefiles)
end

# download shapefiles
url = "https://www.cbs.nl/-/media/cbs/dossiers/nederland-regionaal/wijk-en-buurtstatistieken/wijkbuurtkaart_2020_v1.zip"
name_zipfile = split(url, "/")[end]
path_zipfile = joinpath(pwd(), "downloads", name_zipfile)
if ~isfile(path_zipfile)
    download(url, path_zipfile)
end

# extract shapefiles
path_shapefile = joinpath(pwd(), "shapefiles", "gemeente_2020_v1.shp")
if ~isfile(path_shapefile)
    r = ZipFile.Reader(path_zipfile)
    for file in r.files
        open(joinpath(pwd(), "shapefiles", file.name), "w") do io
            write(io, read(file))
        end
    end
end

# read shapefile
table = Shapefile.Table(path_shapefile)
df = table |> DataFrame

# filter for land (i.e. not water)
row_filter = df.H2O .== "NEE"

# filter data and shapes
municipality_data = df[row_filter, :]
municipality_shape = Shapefile.shapes(table)[row_filter]

function normalize(array)
    """
    Normalize array to values between 0 and 1
    """
    return [(x - minimum(array))/(maximum(array) - minimum(array)) for x in array]
end

# select variable to plot
var = "BEV_DICHTH" # population density

# values to plot
values = municipality_data[:, var]
normalized_values = normalize(values)

# colors
colormap = :heat
colors = Array([cgrad(colormap)[value] for value in normalized_values])

# plot thematic map
p = plot(size=(500, 600), axis=false, ticks=false)
for i = 1:nrow(municipality_data)
    plot!(municipality_shape[i], fill_z=[normalized_values[i] for x in 1:length(municipality_shape[i].points)])
end
p

```

The coloring is not nice but this displays a colorbar.

 ![plot](https://global.discourse-cdn.com/julialang/original/3X/4/3/43131e7f046580cdf50dae9f8d0d22b59757737f.png)

---

<div class="post-metadata">

### Author: ![TheCedarPrince](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/thecedarprince/32/17323_2.png) [@TheCedarPrince](https://discourse.julialang.org/u/TheCedarPrince)
#### Post date: [March 23, 2021, 8:44pm UTC](https://discourse.julialang.org/t/how-do-i-add-a-colorbar-to-a-choropleth-map/57814/3 "2021-03-23T20:44:53Z")

</div>

Hey @lungd! That works beautifully! However, the colors aren’t used anywhere in your above example - I tried a different colormap `gist_yarg` for example - and I cannot get the correct colormap. Any thoughts on what to do to get the right colormap to propagate?

---

<div class="post-metadata">

### Author: ![TheCedarPrince](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/thecedarprince/32/17323_2.png) [@TheCedarPrince](https://discourse.julialang.org/u/TheCedarPrince)
#### Post date: [March 23, 2021, 9:11pm UTC](https://discourse.julialang.org/t/how-do-i-add-a-colorbar-to-a-choropleth-map/57814/4 "2021-03-23T21:11:30Z")

</div>

Happy to report after some tweaking, I figured this out @lungd ! Here is a solution to make everything work and nicely put together:

```julia
choropleth = plot(size = (1000, 600), axis = false, ticks = false)
for i in 1:length(states.geometry)
	plot!(states.geometry[i], fill = :gist_yarg, fill_z = [rand_vals[i] for x in 1:length(states.geometry[i].points)])
end

y = ones(3)
title = Plots.scatter(
    y,
    marker = 0,
    markeralpha = 0,
    annotations = (2, y[2], Plots.text("Rando Plot")),
    axis = ([], false),
    leg = false,
)

plot(
    title,
    choropleth,
    layout = grid(2, 1, heights = [0.10, 0.85]),
)

png(plotsdir("rando.png"))

```

Which produces this plot:

 ![rando](https://global.discourse-cdn.com/julialang/original/3X/1/8/18c022891c17ff1a5cd56e213e5e72529c497719.png)

As a note, I used `DataFrames.jl`, `Shapefile.jl`, and `Plots.jl` to get this all done. 😃 Hope this helps folks out!

---

<div class="post-metadata">

### Author: ![daschw](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/daschw/32/2926_2.png) [@daschw](https://discourse.julialang.org/u/daschw)
#### Post date: [March 24, 2021, 12:46pm UTC](https://discourse.julialang.org/t/how-do-i-add-a-colorbar-to-a-choropleth-map/57814/5 "2021-03-24T12:46:44Z")

</div>

I’ll crosspost my response in the Plots issue ([[BUG] Colorbar Is Missing When Plotting Geometries · Issue #3368 · JuliaPlots/Plots.jl · GitHub](https://github.com/JuliaPlots/Plots.jl/issues/3368)). The intended way to do this is `fill_z` instead of `fillcolor`.

```julia
using DataFrames
using Plots
using Shapefile

states = Shapefile.Table("cb_2018_us_state_5m.shp") |> DataFrame
skip = ["02", "15", "60", "66", "69", "72", "78"]
filter!(row -> !(row[:STATEFP] in skip), states)
sort!(states, [:GEOID])

n = size(states, 1)
plot(states.geometry, fill_z=rand(1, n), title="My title", cbar=true, color=:seismic)

```

![shapes](https://global.discourse-cdn.com/julialang/original/3X/d/1/d181060a36da416c7d7ee2ec355294abd4750128.png)  
Colors are chosen automatically based on the corresponding `fill_z` values from the provided color gradient ([ColorSchemes · Plots](http://docs.juliaplots.org/latest/generated/colorschemes/#ColorGradient)) - in this case `:seismic`, the default is `:inferno` as in @lungd’s example. If you only provide colors as `fillcolor` without corresponding “z” values, Plots can not know how to arrange these colors in a colorbar.

---

<div class="post-metadata">

### Author: ![joa-quim](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/joa-quim/32/227_2.png) [@joa-quim](https://discourse.julialang.org/u/joa-quim)
#### Post date: [March 24, 2021, 1:47pm UTC](https://discourse.julialang.org/t/how-do-i-add-a-colorbar-to-a-choropleth-map/57814/6 "2021-03-24T13:47:54Z")

</div>

You may also want to explore the method exemplified in this GMT [example](https://www.generic-mapping-tools.org/GMT.jl/dev/gallery/choropleths/choropleth_cv19/) and be able to plot beautiful maps with true map projections.

 ![image](https://global.discourse-cdn.com/julialang/original/3X/a/f/af565193283bc51e453cbd1f6d1c3249098dcc56.png)
