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

如何对齐Matplotlib独立图表?解决Y轴标签宽度错位问题

解决Matplotlib独立图表Y轴标签导致错位的问题

问题说明

我用Matplotlib绘制两个独立图表,需分别保存用于不同场景,因此必须保持二者独立。从图表可见,上方图表的Y轴标签占用空间更大,导致两个图表错位。尝试过ax.set_ylabel('Y Axis Label', labelpad=50),但效果不佳。注意:无法更改标签格式(如科学计数法等)。生成单个图表的原函数代码如下:

def prepare_plot(inputDataFrame : pd.DataFrame(), median_columns : list(str()), upper_lower_quantiles : int, labels : list(str())) :
    """
    inputDataFrame: dataframe with values
    median_columns: names of the columns to be used for median values
    upper_lower_quantiles: Delta (1, 2 or 3) compared to the median, if invalid input will default to 1
    labels: labels to be set
    """

    if upper_lower_quantiles not in [1,2,3] : upper_lower_quantiles = 1

    flike = io.BytesIO()

    df = inputDataFrame
    x   = df.index

    fig, ax = plt.subplots()
    fig.set_size_inches(15, 5)

    colors = ['g','r','b']

    for median, label, color in zip(median_columns,labels, colors):

        lower = median[:-1] + f'{3 - upper_lower_quantiles}'
        upper = median[:-1] + f'{3 + upper_lower_quantiles}'
        
        try:
            ax.plot(x, df[median], label=label, color=color)
            ax.fill_between(x,
                            df[lower], #Lower Bound
                            df[upper], #Upper Bound
                            color=color,
                            alpha=.1
                            )
        except:
            print(f'Error on Key ({median}), label ({label}), color ({color})')
            print(f'Not graphing the line')

    ax.grid()
    lgd = ax.legend(loc='center left', bbox_to_anchor=(1.0, 0.5), fontsize=10)
    
    fig.savefig(flike, bbox_extra_artists=(lgd,), bbox_inches='tight')
    b64 = base64.b64encode(flike.getvalue()).decode()
    
    #Saving in a format that is embeddable in  different other platforms
    return b64

解决方案

要让两个独立图表的绘图区域对齐,核心是给每个图表设置统一的左侧留白,确保Y轴标签不管长短,都不会挤压绘图区域的位置。可以通过以下两种方式实现:

  • 方法1:固定子图左侧边距
    在创建图表后,用fig.subplots_adjust()设置固定的左侧边距,数值可根据标签长度调整(比如left=0.12,标签很长时可调大至0.15):

    fig.subplots_adjust(left=0.12)  # 调整数值适配你的标签长度
    
  • 方法2:使用constrained_layout自动适配
    在创建fig, ax时启用constrained_layout=True,让Matplotlib自动调整布局,保证每个图表的留白一致:

    fig, ax = plt.subplots(constrained_layout=True)
    

修改后的完整函数(以方法1为例)

def prepare_plot(inputDataFrame : pd.DataFrame(), median_columns : list(str()), upper_lower_quantiles : int, labels : list(str())) :
    """
    inputDataFrame: dataframe with values
    median_columns: names of the columns to be used for median values
    upper_lower_quantiles: Delta (1, 2 or 3) compared to the median, if invalid input will default to 1
    labels: labels to be set
    """

    if upper_lower_quantiles not in [1,2,3] : upper_lower_quantiles = 1

    flike = io.BytesIO()

    df = inputDataFrame
    x   = df.index

    fig, ax = plt.subplots()
    fig.set_size_inches(15, 5)
    # 新增:固定左侧边距,确保Y轴标签有足够空间且布局统一
    fig.subplots_adjust(left=0.12)

    colors = ['g','r','b']

    for median, label, color in zip(median_columns,labels, colors):

        lower = median[:-1] + f'{3 - upper_lower_quantiles}'
        upper = median[:-1] + f'{3 + upper_lower_quantiles}'
        
        try:
            ax.plot(x, df[median], label=label, color=color)
            ax.fill_between(x,
                            df[lower], #Lower Bound
                            df[upper], #Upper Bound
                            color=color,
                            alpha=.1
                            )
        except:
            print(f'Error on Key ({median}), label ({label}), color ({color})')
            print(f'Not graphing the line')

    ax.grid()
    lgd = ax.legend(loc='center left', bbox_to_anchor=(1.0, 0.5), fontsize=10)
    
    fig.savefig(flike, bbox_extra_artists=(lgd,), bbox_inches='tight')
    b64 = base64.b64encode(flike.getvalue()).decode()
    
    #Saving in a format that is embeddable in  different other platforms
    return b64

补充说明

  • 方法1优势是完全可控,可根据最长的Y轴标签调整left数值,确保所有图表左侧留白一致;
  • 方法2更自动化,适合标签长度差异不大的场景,无需手动调整数值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 02:50:42