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

Julia使用gr()绘制子图时宽度不一致问题求助

问题:Plots子图拼接后宽度不均匀

环境

  • Linux系统
  • Julia 1.11.7(已测试1.10.1)
  • Plots v1.41.1

复现代码

using Plots; gr()
 
titles = hcat(["X "*string(x) for x in collect(15:-1:8)'], ["X "*string(x) for x in collect(0:7)'])
 
flag_seq = [false, true, true, true, false, false, true, true,
            true, false, true, true, true, false, true, false]
 
sub_plots = Any[]
for flag in flag_seq
    if flag == true
        push!(sub_plots, Plots.hspan([0,1],[0,1], color=:lightgreen, label="", axis=:none, ticks=:false, framestyle=:none))
    elseif flag == false
        push!(sub_plots, Plots.hspan([0,1],[0,1], color=:red, label="", axis=:none, ticks=:false, framestyle=:none))
    end
end
subplots = Plots.plot(sub_plots..., layout = (2,8), title=titles, titlefont=8)
Plots.plot!(subplots, alpha=0.75, legend=:false,size=(500, 150), ticks=:false, box=:none, margin=-1Plots.mm, top_margin=1Plots.mm)
Plots.savefig("subplot_intermediate.png")
 
title_plot = Plots.plot(title="Overall Title", grid=false, showaxis=false)
combo_plot = Plots.plot(title_plot, subplots, layout=@layout([A{0.01h}; B]), size=(500, 175))   #@layout([A{0.01h}; B])
Plots.savefig("combo.png")

问题现象

最终生成的combo.png中子图宽度不均匀(X0、X15最明显,X7、X8也可见),但中间产物subplot_intermediate.png显示正常。调整布局、尺寸等操作后问题仍存在。

解决思路

  • 避免二次布局拼接,直接添加总标题:问题核心是通过@layout拼接标题图和子图时,Plots的布局引擎会重新计算子图宽度,破坏了原始子图的均匀布局。可以直接在生成subplots时添加总标题,无需额外创建title_plot。修改示例:

    # 替换原plot!和后续拼接代码
    Plots.plot!(subplots, alpha=0.75, legend=:false, size=(500, 175), ticks=:false, box=:none, margin=-1Plots.mm, top_margin=5Plots.mm, title="Overall Title", titlefont=10)
    Plots.savefig("combo.png")
    
  • 强制固定子图宽度比例:若必须使用布局拼接,可在layout中明确指定子图的宽度分配。将subplots的布局改为grid(2,8, widths=fill(1/8, 8)),强制每个子图占据1/8的宽度,再进行拼接:

    # 生成subplots时修改布局
    subplots = Plots.plot(sub_plots..., layout = grid(2,8, widths=fill(1/8,8)), title=titles, titlefont=8)
    # 后续拼接代码不变
    
  • 统一标题宽度或对齐方式:X0、X15等标题长度差异会触发布局引擎自动调整子图宽度。可设置titlealign=:center让标题居中对齐,或给短标题添加空白填充(比如将"X 0"改为"X 0 "),使所有标题宽度一致,避免布局偏移。

内容的提问来源于stack exchange,提问作者Jen-Feng Hsu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 06:33:28