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

Python中使用ax函数编辑图例:解决无标签错误并添加红线

0维持久化图:图例优化与报错修复

问题说明

  • 需求:右侧子图(ax2)的图例标题“current radius = {i}”左侧添加一条水平红线
  • 报错:执行ax2.legend(loc = 'lower right', title = f'current radius = {i}')时,触发错误提示:
    No artists with labels found to put in legend. Note that artists whose label start with an underscore are ignored when legend() is called with no argument.
    

解决方案

报错原因

报错是因为当前子图ax2中没有带有label属性的绘图元素,matplotlib的legend默认需要基于带label的元素生成图例,空调用就会触发该错误。

实现方案

手动创建一个红色的图例元素(色块),将其添加到legend中,同时设置标题,既解决报错,又实现标题左侧带红线的效果。

修改后的完整代码

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from celluloid import Camera
import numpy as np

# 初始圆心坐标
h = 0       # x坐标
k = 0       # y坐标

# 随机生成的角度集合
theta = np.array( [1 * np.pi / 6, 2 * np.pi / 3, 4 * np.pi / 5, 
                   1 * np.pi / 5, 2 * np.pi / 5, 4 * np.pi / 7,
                   1 * np.pi / 4, 2 * np.pi / 9, 4 * np.pi / 3,
                   1 * np.pi / 3, 3 * np.pi / 2, 5 * np.pi / 9, 
                   1 * np.pi / 2, 3 * np.pi / 8, 5 * np.pi / 4,
                   1 * np.pi / 1, 3 * np.pi / 7, 5 * np.pi / 3,
                   11 * np.pi / 6, 11 * np.pi / 10, 7 * np.pi / 6,
                   11 * np.pi / 7,  7 * np.pi /  4, 1 * np.pi / 10] )


# 计算随机点坐标
r = np.linspace(.1,2,24)        # 控制点扩散范围的半径向量
x = h + r * np.cos(theta)
y = k + r * np.sin(theta)

# 持久化图参数设置
radii = np.linspace(0,1,50)                                  # 完整半径序列
trunc_radii = np.around(radii, 3)                            # 保留三位小数的半径序列
death_list = np.array( [.041, .061, .102, .122, .143,        # 触发点消亡的半径值
                        .163, .184, .224, .245, .286,
                        .306, .327, .408, .429, .694] )

plotted_deaths = []                                          # 已绘制的消亡点记录

fig, (ax1, ax2) = plt.subplots(1,2)
camera = Camera(fig)

for i in trunc_radii :
    ax1.scatter(x, y, color = 'green', marker = 'o', s = 15)

    for xx,yy in zip(x,y) :
        cir = mpatches.Circle((xx, yy), i, color = 'r',fill = True, zorder = 0)
        ax1.add_patch(cir)

    ax1.set_aspect('equal', adjustable='datalim')
    ax1.set_title('平面随机点')
    ax1.set(xlabel='x轴', ylabel='y轴')
    ax1.set_xlim([-2.25, 2.25])
    ax1.set_ylim([-2.25, 2.25])

    a = np.arange(0,1.1,.1)
    b = a
    ax2.plot(a,b, color = 'b')
    ax2.axhline(y = i, color = 'r', linestyle = '-')

    if i in death_list :
        plotted_deaths.append(i)

    for j in plotted_deaths :
        ax2.plot(0, j, marker = "o", markersize = 5, markeredgecolor = "green", markerfacecolor = "green")

    ax2.set_aspect('equal', adjustable='datalim')
    ax2.set_title('0维持久化图')
    ax2.set(xlabel='诞生', ylabel='消亡')
    
    # --- 核心修改:解决报错并添加红线图例 ---
    # 创建红色色块作为图例标识,label设为空仅展示色块
    red_legend_patch = mpatches.Patch(color='red', label='')
    # 传入handles指定图例元素,同时设置标题
    ax2.legend(handles=[red_legend_patch], loc='lower right', title=f'当前半径 = {i}')

    fig.set_figheight(6)
    fig.set_figwidth(12)

    camera.snap()

animation = camera.animate()
# animation.save('平面随机点的0维持久化图.gif')
plt.show()

关键修改点

  1. 手动创建mpatches.Patch红色元素,作为图例的显示项,解决了“无带label元素”的报错问题
  2. 通过将红色Patch放入legend的handles参数中,实现了标题左侧带红色标识的效果
  3. 额外将界面文字改为中文,提升可读性(可根据需求改回英文)

内容的提问来源于stack exchange,提问作者The Mad Scientist

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 14:30:42