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

如何为Matplotlib子图添加方程图例?Python新手求助

解决Matplotlib二次曲线子图添加方程图例的问题

你的问题出在contour绘图时未给曲线绑定对应label,且部分子图未调用legend()方法。另外可以利用Matplotlib的LaTeX支持渲染规范的数学公式,让图例更清晰专业。

修改后的完整代码

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

# 配置全局样式,开启LaTeX支持
mpl.rcParams['lines.color'] = 'k'
mpl.rcParams['axes.prop_cycle'] = mpl.cycler('color', ['k'])
mpl.rcParams['text.usetex'] = True  # 启用LaTeX渲染数学公式

x = np.linspace(-9, 9, 400)
y = np.linspace(-5, 5, 400)
x, y = np.meshgrid(x, y)

def axes(ax):
    ax.axhline(0, alpha=0.1)
    ax.axvline(0, alpha=0.1)

fig, ax = plt.subplots(2, 2, figsize=(10, 8))
fig.suptitle("二次曲线可视化:抛物线、圆、椭圆、双曲线", fontsize=14)

# 抛物线
a = 0.3
axes(ax[0,0])
contour_p = ax[0,0].contour(x, y, (y**2 - 4*a*x), [2], colors='k', 
                            label=r'$y^2 = 4ax \quad (a=0.3)$')
ax[0,0].set_ylabel('抛物线')
ax[0,0].legend(handles=[contour_p.collections[0]], loc='best')

# 圆
a = 2
b = 2
axes(ax[0,1])
contour_c = ax[0,1].contour(x, y, (x**2/a**2 + y**2/b**2), [1], colors='k',
                            label=r'$\frac{x^2}{a^2} + \frac{y^2}{b^2} = 1 \quad (a=b=2)$')
ax[0,1].set_title('圆')
ax[0,1].legend(handles=[contour_c.collections[0]], loc='best')

# 椭圆
a = 4
b = 2
axes(ax[1,0])
contour_e = ax[1,0].contour(x, y, (x**2/a**2 + y**2/b**2), [1], colors='k',
                            label=r'$\frac{x^2}{a^2} + \frac{y^2}{b^2} = 1 \quad (a=4, b=2)$')
ax[1,0].set_ylabel('椭圆')
ax[1,0].legend(handles=[contour_e.collections[0]], loc='best')

# 双曲线
a = 2
b = 1
axes(ax[1,1])
contour_h = ax[1,1].contour(x, y, (x**2/a**2 - y**2/b**2), [1], colors='k',
                            label=r'$\frac{x^2}{a^2} - \frac{y^2}{b^2} = 1 \quad (a=2, b=1)$')
ax[1,1].set_ylabel('双曲线')
ax[1,1].legend(handles=[contour_h.collections[0]], loc='best')

plt.tight_layout()
plt.subplots_adjust(top=0.9)  # 调整顶部间距,避免标题被遮挡
plt.show()

关键修改点说明

  1. LaTeX渲染支持:通过mpl.rcParams['text.usetex'] = True启用LaTeX,让图例中的数学公式显示更规范美观。
  2. 绑定曲线label:给每个contour调用添加label参数,传入LaTeX格式编写的方程。
  3. 关联图例条目:contour返回的是ContourSet对象,需通过collections[0]提取对应曲线对象,传入legend()的handles参数才能正确显示图例。
  4. 布局优化:添加plt.tight_layout()和subplots_adjust避免子图元素重叠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 15:40:50