You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调整CairoMakie中子图大小,使散点图占75%的横竖空间?

调整CairoMakie子图布局,让散点图占据75%空间

问题背景

使用CairoMakie绘制了包含密度图与散点图的可视化,原代码如下:

using CairoMakie

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

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

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)
fig

需要调整子图布局,让散点图(ax3)占据75%的水平和垂直空间。

解决方案

通过修改Figure布局的行高和列宽比例,实现目标效果:

修改后的完整代码

using CairoMakie

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

fig = Figure(resolution = (1200, 800), font = "sans", fontsize = 20)
# 设置行高比例:第一行占25%,第二行占75%(散点图所在行)
fig.layout.heights = [Relative(0.25), Relative(0.75)]
# 设置列宽比例:第一列占75%(散点图所在列),第二列占25%
fig.layout.widths = [Relative(0.75), Relative(0.25)]

ax1 = Axis(fig[1, 1])
density!(ax1, y; bins = 20, color = :orange, strokewidth = 1,
    strokecolor = :black, label = "20 bins")
axislegend(ax1)

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)
axislegend(ax4)

fig

关键调整说明

  • 垂直空间控制:通过fig.layout.heights定义行的相对高度,Relative(0.25)对应顶部密度图的行高占比,Relative(0.75)对应散点图和右侧密度图所在行的占比,确保散点图垂直方向占75%空间。
  • 水平空间控制:通过fig.layout.widths定义列的相对宽度,Relative(0.75)对应散点图所在列的占比,Relative(0.25)对应右侧密度图的列宽占比,实现散点图水平方向占75%空间。
  • 若需更复杂的嵌套布局,可单独创建GridLayout对象进行精细化管理,上述方法为最简洁的直接调整方式。

内容的提问来源于stack exchange,提问作者Alec

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 19:36:17