首页 > 解决方案 > 如何为两个函数交集的区域编写标题?

问题描述

假设c[0,0.5]r=sqrt(c)

我正在使用以下代码填充 和 之间的区域0r并且我想在图中的该区域内写标签:

fig, ax1 = plt.subplots(1, 1, sharex=True);
ax1.fill_between(c, 0, r, label='region 1 ')

怎么可能做到这一点?

另外,当我设置时c=constant,它会产生一条线,我愿意将它显示为一条带有图例的实线。我怎样才能做到这一点?

新年快乐!

标签: pythonmatplotlib

解决方案


ax.legend()可以为每个带有label=.... 可以设置以“轴坐标”测量bbox_to_anchor=(x,y)的锚点(从左侧绘图边界到右侧的 1,从底部的 0 到顶部的 1)。告诉图例边界框的哪个点将定位在锚点处。x,yloc=

ax.axhline()绘制一条恒定的水平线。

import matplotlib.pyplot as plt
import numpy as np

c = np.linspace(0, 0.5)
r = np.sqrt(c)
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 4))
ax1.fill_between(c, 0, r, label='region 1')
ax1.legend(loc='lower right', bbox_to_anchor=(0.8, 0.2), facecolor='ivory', framealpha=0.9)
ax1.margins(x=0, y=0)
constant = 0.5
ax2.axhline(np.sqrt(constant), label=f'sqrt of {constant}', lw=2)
ax2.legend()
ax2.set_xlim(0, 0.5)
ax2.set_ylim(0, 1)
plt.show()

结果图


推荐阅读