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

如何让Matplotlib中annotate()的输出效果与print()一致?

如何让Matplotlib的annotate()输出与print()保持一致?

当文本包含大量空格和缩进时,print()的输出能保持正确的排版对齐,但plt.annotate()的显示效果会出现错乱,比如缩进丢失、表格列不对齐等问题。以下是对比代码及现象:

对比代码

from matplotlib import pyplot as plt
import json

with open("epoch_3350-20230218172431.json", "r") as source:
    log_dict = json.load(source)
    print(log_dict["model_structure"])
    plt.figure(figsize=(25, 10))
    plt.annotate(text=f"{log_dict.get('model_structure').__str__()}",
                   xy=(0.08, 0.5), bbox={'facecolor': 'green', 'alpha': 0.4, 'pad': 5},
                   fontsize=14, xycoords='axes fraction', va='center')
    plt.show()
    plt.close()
MTSCorrAD(
  (gin_convs): ModuleList(
    (0): GINConv(nn=Sequential(
      (0): Linear(in_features=1, out_features=3, bias=True)
      (1): BatchNorm1d(3, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (2): ReLU()
      (3): Linear(in_features=3, out_features=3, bias=True)
      (4): ReLU()
    ))
  )
  (gru1): GRU(3, 8)
  (lin1): Linear(in_features=8, out_features=3, bias=True)
)
====================================================================================================
+-------------------------+-----------------------------+-----------------+----------+
| Layer                   | Input Shape                 | Output Shape    |   #Param |
|-------------------------+-----------------------------+-----------------+----------|
| MTSCorrAD               | [792, 1], [2, 52272], [792] | [3]             |      363 |
| ├─(gin_convs)ModuleList | --                          | --              |       24 |
| │    └─(0)GINConv       | [792, 1], [2, 52272]        | [792, 3]        |       24 |
| ├─(gru1)GRU             | [12, 3]                     | [12, 8], [1, 8] |      312 |
| ├─(lin1)Linear          | [8]                         | [3]             |       27 |
+-------------------------+-----------------------------+-----------------+----------+

annotate()的问题

当前plt.annotate()的输出会出现缩进压缩、表格列错位等情况,无法还原print()的排版效果。

解决方法

核心问题是Matplotlib默认使用非等宽字体,导致空格和字符宽度不一致,同时文本对齐方式未正确设置。修改代码如下:

from matplotlib import pyplot as plt
import json

with open("epoch_3350-20230218172431.json", "r") as source:
    log_dict = json.load(source)
    model_str = log_dict["model_structure"].__str__()
    print(model_str)
    plt.figure(figsize=(25, 10))
    plt.annotate(text=model_str,
                   xy=(0.08, 0.5), 
                   bbox={'facecolor': 'green', 'alpha': 0.4, 'pad': 5},
                   fontsize=14, 
                   xycoords='axes fraction', 
                   va='center',
                   fontfamily='monospace',  # 使用等宽字体
                   multialignment='left')   # 多行左对齐
    plt.show()
    plt.close()

关键修改说明

  • fontfamily='monospace':设置等宽字体,让每个字符(包括空格)的宽度完全一致,确保缩进和表格对齐正确。
  • multialignment='left':强制每行文本左对齐,和print()的输出逻辑保持一致。
  • 直接使用原始字符串model_str,避免多余的格式化操作破坏原有排版。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 16:06:28