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

如何在Matplotlib绘图边缘外侧绘制标记点?

在Matplotlib折线图边缘末端外侧添加标记点

我用以下代码生成了Matplotlib折线图:

import numpy as np
import matplotlib.pyplot as plt
if __name__ == "__main__":
    res_files=([1],[2],[3],[4])
    marker_list = ['bo-', 'gv-', 'rD--', 'c*--', 'mh:', 'ys:']
    label_list = ['a', 'b', 'c', 'd','e']
    fig, ax = plt.subplots()
    j = 0
    for i, res in enumerate(res_files):
        data = res_files  # 此处存在错误,应取当前循环的res而非整个res_files
        x = np.arange(0, len(data))
        ax.plot(x, data, marker_list[i], label=label_list[j])
        j = (j + 1)
plt.xticks(np.arange(0, len(data), 1.0))
ax.set_xlim(0, 3)
plt.ylabel('abc')
plt.xlabel('dcf')
plt.legend(loc='upper left')
plt.grid(which='major', linestyle='-', linewidth='0.05', color='black')
plt.show()

我希望在绘图边缘的末端外侧绘制两个标记点,达到目标示例图的效果,该如何操作?


实现方法

核心思路是获取每条折线的末端数据,在绘图区域外侧的位置绘制独立标记,同时调整坐标轴范围让标记完整显示。具体步骤如下:

  1. 修正原代码的数据赋值错误,确保每条折线对应正确的数据集;
  2. 记录每条折线的末端y值及对应标记样式;
  3. 设置超出原绘图范围的x坐标作为外侧标记的位置;
  4. 用scatter()绘制外侧标记,保持与对应折线的样式统一;
  5. 扩大x轴范围,避免外侧标记被截断。

完整修改代码

import numpy as np
import matplotlib.pyplot as plt

if __name__ == "__main__":
    res_files = ([1], [2], [3], [4])
    marker_list = ['bo-', 'gv-', 'rD--', 'c*--', 'mh:', 'ys:']
    label_list = ['a', 'b', 'c', 'd', 'e']
    fig, ax = plt.subplots()
    
    # 存储每条折线的末端y值、颜色和标记符号
    end_info = []
    
    for i, res in enumerate(res_files):
        data = res
        # 让每条折线对应x轴上的0、1、2、3位置
        x = np.array([i])
        line_style = marker_list[i]
        ax.plot(x, data, line_style, label=label_list[i])
        # 提取标记的颜色和符号
        marker_color = line_style[0]
        marker_symbol = line_style[1]
        end_info.append((data[0], marker_color, marker_symbol))
    
    # 设置外侧标记的x坐标(超出原x轴上限3)
    outer_x = 3.2
    # 绘制外侧标记
    for y, color, symbol in end_info:
        ax.scatter(outer_x, y, marker=symbol, color=color, s=60)
    
    # 调整x轴范围,确保外侧标记显示完整
    ax.set_xlim(-0.2, 3.5)
    plt.xticks(np.arange(0, len(res_files), 1.0))
    plt.ylabel('abc')
    plt.xlabel('dcf')
    plt.legend(loc='upper left')
    plt.grid(which='major', linestyle='-', linewidth='0.05', color='black')
    plt.show()

关键说明

  • 修正了原代码中data = res_files的错误,确保每条折线对应独立的数据集;
  • 通过end_info列表记录折线末端的样式信息,保证外侧标记与折线风格一致;
  • 调整ax.set_xlim()扩大x轴右侧范围,避免外侧标记被坐标轴截断;
  • 使用scatter()的s参数可以调整标记大小,优化视觉效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 02:57:04