How to draw heatmap with DataFrames

Let’s say I have a data frame like this, how do I make a heatmap? I’m already using StatPlots so that would be the preferred way. I tried to look up documentation but couldn’t find it…

data = DataFrame(
    src = ["London", "London", "New York", "Hong Kong"],
    dst = ["Beijing", "New York", "Boston", "Boston"],
    val = [1000.00, 2000.00, 3000.00, 4000.00]
)
1 Like

There is not enough data to draw a heat map. What do you want the plot to look like?

The data above is just a sample. I worked that out manually but was hoping for an easier/existing solution. Here’s what I did:

# Return data required for heatmap
function make_heatmap_data(data, x, y, v)
    xs = unique(data[x])
    ys = unique(data[y])
    n = length(xs)
    m = length(ys)
    A = zeros((n, m))
    D1 = Dict(x => i for (i,x) in enumerate(xs))
    D2 = Dict(x => i for (i,x) in enumerate(ys))
    for i in 1:size(data, 1)
        xi = data[i, x]
        yi = data[i, y]
        vi = data[i, v]
        A[D1[xi], D2[yi]] = vi
    end
    (xs, ys, A)
end

let (x, y, A) = make_heatmap_data(data, :src, :dst, :val)
    heatmap(x, y, A, seriescolor = :blues, size = (400,300))
end

heatmap_example

2 Likes

Here is how you can do it with VegaLite.jl:

data |> @vlplot(:rect, x=:src, y=:dst, color=:val)

That gets me:
visualization%20(2)

Probably worth playing around a bit more with the size of the plot etc., but I also assume that would just look better with more data.

2 Likes