matplotlib:曲线标签

o75abkj4  于 2022-12-23  发布在  其他
关注(0)|答案(1)|浏览(184)

当我创建一个有很多曲线的图时,如果能在每个曲线结束的地方给它贴上标签会很方便。
plt.legend的结果产生太多相似的颜色,图例与图重叠。
从下面的示例中可以看出,使用plt.legend不是很有效:

import numpy as np
from matplotlib import pyplot as plt

n=10
x = np.linspace(0,1, n)

for i in range(n):
   y = np.linspace(x[i],x[i], n)
   plt.plot(x, y, label=str(i))
   
plt.legend(loc='upper right')

plt.show()

如果可能的话,我想有类似于这个情节:

或者这个:

gfttwv5a

gfttwv5a1#

我推荐使用answer suggested in the comments,但另一种方法与第一种方法类似(尽管图例标记的位置与关联线的位置不匹配),该方法是:

import numpy as np

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

n=10
x = np.linspace(0, 1, n)
labels = [str(i) for i in range(len(x))]

for i in range(n):
    y = np.linspace(x[i], x[i], n)
    ax.plot(x, y, label=labels[i])

h, _ = ax.get_legend_handles_labels()

# sort the legend handles/labels so they are in the same order as the data
hls = sorted(zip(x, h, labels), reverse=True)

ax.legend(
    [ha[1] for ha in hls],  # get handles
    [la[2] for la in hls],  # get labels
    bbox_to_anchor=(1.04, 0, 0.1, 1),  # set box outside of axes
    loc="lower left",
    labelspacing=1.6,  # add space between labels
)

leg = ax.get_legend()

# expand the border of the legend
fontsize = fig.canvas.get_renderer().points_to_pixels(leg._fontsize)
pad = 2 * (leg.borderaxespad + leg.borderpad) * fontsize
leg._legend_box.set_height(leg.get_bbox_to_anchor().height - pad)

这在很大程度上依赖于herehere的答案。

相关问题