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

Python f-string如何实现基于空格而非字符数的填充对齐?

解决非等宽字体下Matplotlib图例标签的对齐问题

问题背景

之前用f-string按字符数填充空格(比如{project_name:<10})来对齐图例标签的“n=”部分,但因为使用的是非等宽字体,不同前缀(如foo和fii)的字符宽度不一样,导致后面的内容无法精准对齐,达不到所有标签“n=”部分左对齐的效果。

解决方案:基于文本实际宽度动态填充空格

核心思路是利用Matplotlib的文本渲染器,计算前缀文本的实际显示宽度,再动态补充足够的空格,让前缀+空格的总宽度固定,从而保证后续内容对齐。

实现代码

import matplotlib.pyplot as plt

# 创建绘图对象,获取渲染器
fig, ax = plt.subplots()
renderer = fig.canvas.get_renderer()

# 定义函数:计算文本的实际显示宽度
def calc_text_width(text):
    text_obj = plt.text(0, 0, text)
    width = text_obj.get_window_extent(renderer=renderer).width
    text_obj.remove()
    return width

# 设定前缀区域的目标总宽度(可根据需求调整,这里以10个空格的宽度为基准)
target_prefix_width = calc_text_width(' ' * 10)

# 示例数据
project_list = ["foo", "fii", "long_proj_name"]
sample_size = 80
rho_value = 0.62

# 生成对齐后的标签
aligned_labels = []
for proj_name in project_list:
    # 计算当前前缀的宽度
    current_width = calc_text_width(proj_name)
    # 计算需要补充的空格数
    single_space_width = calc_text_width(' ')
    needed_spaces = max(0, int((target_prefix_width - current_width) / single_space_width) + 1)
    # 拼接标签
    label = f"{proj_name}{' ' * needed_spaces}n={sample_size}: rho={rho_value:.2f}"
    aligned_labels.append(label)

# 绘图并添加图例
ax.plot([1,2,3], label=aligned_labels[0])
ax.plot([2,3,5], label=aligned_labels[1])
ax.plot([3,4,6], label=aligned_labels[2])
ax.legend()
plt.show()

说明

  1. 该方法通过get_window_extent获取文本的实际像素宽度,确保前缀区域的总显示宽度一致,不受字体字符宽度差异影响。
  2. 可以通过调整target_prefix_width的值来控制前缀区域的宽度,比如增大数值让标签布局更宽松。
  3. 如果使用了自定义字体,只需在calc_text_width函数的plt.text中传入对应的fontprops参数即可适配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 19:27:16