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

如何在Python的Matplotlib绘图中扩展坐标轴并显示标注文字?

在Matplotlib中优化图表标注可见性与坐标轴空间的方法

针对你遇到的标注被遮挡、坐标轴空间不足的问题,可以通过以下调整解决:

一、让标注文字清晰可见

给标注添加偏移量避免和散点重叠,同时可按需调整字体大小:

  • 在plt.annotate中加入xytext参数设置偏移(比如向上偏移5个点),并指定textcoords='offset points'定义偏移单位
  • 可选:通过fontsize调整标注字体大小,平衡可读性和空间占用

二、优化坐标轴空间

  • 手动扩展x轴范围,给两端标注留足空间,用plt.xlim()设置比数据极值更宽的区间
  • 调整图表边距,通过plt.subplots_adjust设置合适的bottom/left/right值,避免标注被截断
  • 即使隐藏了y轴,也可以微调y轴范围,给上下方向的标注留空间

修改后的完整代码

import matplotlib.pyplot as plt
import numpy as np

# 假设movement_speed_scores和movement_list是已定义的变量
plt.scatter(movement_speed_scores, np.zeros_like(movement_speed_scores), s=10, color="blue")

for i, txt in enumerate(movement_list):
    # 添加标注偏移,避免和散点重叠
    plt.annotate(txt, 
                 (movement_speed_scores[i], np.zeros_like(movement_speed_scores)[i]),
                 xytext=(0, 5),  # 向上偏移5个点
                 textcoords='offset points',
                 fontsize=8)  # 按需调整字体大小

# 扩展x轴范围,取数据最小/最大值±10%的余量
x_min = np.min(movement_speed_scores) * 0.9
x_max = np.max(movement_speed_scores) * 1.1
plt.xlim(x_min, x_max)

# 调整图表边距,给底部和两侧留空间
plt.subplots_adjust(bottom=0.2, left=0.1, right=0.9)

# 隐藏y轴刻度
plt.yticks([])
# 微调y轴范围,给标注留上下空间
plt.ylim(-0.1, 0.2)

plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 04:55:42