Overlaying Plots on Heatmaps in Julia
Code
Let’s say we want to draw a sine curve from $0$ to $2\pi$ on the heatmap of the array $(5,5)$. You might want to write the code like this, but as you can see in the figure, it doesn’t output as desired.
using Plots
A = rand(Bool, 5,5)
heatmap(A, color=:greens)
x = range(0, 2pi, length=100)
y = sin.(x)
plot!(x, y, color=:red, width=3)
This is because the horizontal and vertical range of array $A$ is recognized as from $1$ to $5$. To solve this, you can specify the horizontal and vertical range of $A$ as below. Note that if you do not specify the range of array $A$ and only specify the range shown in the heatmap, it will be displayed as below.
xₐ = range(0,2pi, length=5)
yₐ = range(-1.5,1.5, length=5)
p1 = heatmap(xₐ, yₐ, A, color=:greens, xlims=(0,2pi), ylims=(-1.5,1.5)) #그림 (가)
p2 = heatmap(A, color=:greens, xlims=(0,2pi), ylims=(-1.5,1.5)) #그림 (나)
Now, if we redraw the sine curve on p1
, it is drawn correctly as desired.
plot!(x, y, color=:red, width=3)
Environment
- OS: Windows10
- Version: Julia 1.7.1, Plots 1.25.3