Search code examples
plotjuliamakie.jl

How to fix aspect ratio with linked axes?


I'm trying to make a scatterplot with marginal density, and have the scatterplot have fixed x and y limits with an aspect ratio equal to 1. However, I can't seem to find a combination of axis linking, axis limits, and colsize that fits this.

This is close, but note that the scatter plot does not have equal axes:

using CairoMakie

n = 3000
r = randn(2,3000)
x = @view r[1,:]
y = @view r[2,:]

fig = Figure(resolution = (1000, 1000), font = "sans", fontsize = 20)
ax1 = (Axis(fig[1, 1]))
density!(ax1, y; bins = 20, color = :orange, strokewidth = 1,
    strokecolor = :black, label = "20 bins", aspect=1)

ax3 = Axis(fig[2, 1]; xlabel = "value", ylabel = "counts")
ax4 = Axis(fig[2, 2]; xlabel = "value", ylabel = "counts")
scatter!(ax3, x, y; markersize = 4, color = :black,label="samples")
axislegend(ax3; position = :rt)

density!(ax4, x; label = "default",direction=:y)
rowsize!(fig.layout, 2, Auto(3))
colsize!(fig.layout, 1, Auto(3))
xlims!(ax3,-4,4)
ylims!(ax3,-4,4)
linkxaxes!(ax1, ax3)
linkyaxes!(ax3, ax4)


fig

Produces:

enter image description here

This is a followup question from this post: Change the size of a sub-figure?


Solution

  • You need to add aspect_ratio=1 to the scatter plot (credit to @mikael-Öhman):

    using CairoMakie
    
    n = 3000
    r = randn(2,3000)
    x = @view r[1,:]
    y = @view r[2,:]
    
    fig = Figure(resolution = (1000, 1000), font = "sans", fontsize = 20)
    ax1 = (Axis(fig[1, 1]))
    density!(ax1, y; bins = 20, color = :orange, strokewidth = 1,
        strokecolor = :black, label = "20 bins", aspect=1,aspect_ratio=1)
    
    ax3 = Axis(fig[2, 1]; xlabel = "value", ylabel = "counts")
    ax4 = Axis(fig[2, 2]; xlabel = "value", ylabel = "counts")
    scatter!(ax3, x, y; markersize = 4, color = :black,label="samples")
    axislegend(ax3; position = :rt)
    
    density!(ax4, x; label = "default",direction=:y)
    rowsize!(fig.layout, 2, Auto(3))
    colsize!(fig.layout, 1, Auto(3))
    xlims!(ax3,-4,4)
    ylims!(ax3,-4,4)
    linkxaxes!(ax1, ax3)
    linkyaxes!(ax3, ax4)
    
    
    fig