You need to enable JavaScript to run this app. matplotlib中ax.annotate多行字符串左对齐错位问题如何解决
优惠活动
大模型
产品
解决方案
定价
更多

matplotlib中ax.annotate多行字符串左对齐错位问题如何解决

解决matplotlib多行注释左对齐偏移问题

问题根因

你定义的多行格式化字符串中,第二行及后续每行行首都保留了代码编写时的缩进空格,这些空格属于字符串内容的一部分,左对齐渲染时就会出现明显的右偏移;右对齐时空格位于每行尾部,视觉上不会影响对齐效果。

解决方案

方案1:自动清理公共缩进(最推荐)

使用Python标准库textwrap.dedent自动移除多行字符串所有行的公共前导缩进,不需要调整原有字符串的编写格式:

# 先导入依赖
from textwrap import dedent

# 用dedent包裹原有多行字符串
annotation_string = dedent("""Excel file name: {0}
        Sheet name: {1}
        
        No.of Iterations: {2}
        Cp = {3}
        CpK = {4}
        
        Mean = {11}
        Standard Deviation = {12}
        
        The smallest simulated value is {5}
        The largest simulated value is {6}
        
        The 4sigma limit is from {7} to {8}
        The 5sigma limit is from {9} to {10}
        """.format(filename,sheet,iterations,round(cp,4),round(cpk,4),smallest_val,
                  largest_val,round(mean_minor_sigma[3],5),round(mean_sigma[3],5),
                   round(mean_minor_sigma[4],5),round(mean_sigma[4],5),round(mittelwert,4),round(sigma,4)))

原有ax1.annotate代码不需要修改,保留horizontalalignment='left'即可正常左对齐。

方案2:手动调整字符串格式

编写多行字符串时,去掉后续行的额外前导缩进:

annotation_string = """Excel file name: {0}
Sheet name: {1}

No.of Iterations: {2}
Cp = {3}
CpK = {4}

Mean = {11}
Standard Deviation = {12}

The smallest simulated value is {5}
The largest simulated value is {6}

The 4sigma limit is from {7} to {8}
The 5sigma limit is from {9} to {10}
""".format(filename,sheet,iterations,round(cp,4),round(cpk,4),smallest_val,
           largest_val,round(mean_minor_sigma[3],5),round(mean_sigma[3],5),
           round(mean_minor_sigma[4],5),round(mean_sigma[4],5),round(mittelwert,4),round(sigma,4))

方案3:显式指定内部对齐规则

如果不想修改字符串内容,可以在annotate方法中新增multialignment='left'参数,指定文本块内部多行的对齐规则:

ax1.annotate(annotation_string, xy=(0.65, 0.65), xycoords='axes fraction',
                                             backgroundcolor='r', fontsize=14,
                                             horizontalalignment='left',
                                             multialignment='left')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 03:15:06