为什么 Python 中带有标签的句柄会出现错误?

Why is there an error regarding handles with labels in Python?

我正在尝试从 .txt 文件中绘图,但在执行图例时出现错误。我不确定这里的错误是什么。这是代码:

# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
plt.close('all')

#-----------------------------------------------------------------------
# read data
#-----------------------------------------------------------------------
DATA_PATH = '/home/public/WS1819_Ex3/experiments/exercise_02/Absorption.txt'
data = np.genfromtxt(DATA_PATH, skip_header=1)
x, y1, y2, y3 = data[:,0], data[:,1], data[:,2], data[:,3]

#-----------------------------------------------------------------------
# prepare canvas
#-----------------------------------------------------------------------

fig, ax = plt.subplots(1, 1)
ax.grid(True)
ax.set_xlabel('Abstand [cm]')
ax.set_ylabel(u'Intensität [V]')
ax.set_title(u'Absorption von Licht in Wasser')
# set logarithmic y-scale
ax.set_yscale('log')
#-----------------------------------------------------------------------
# plot data
plt.plot(x,y1)
plt.show()

ax.legend()
fig.savefig('Absorption.pdf')

这是输出:

OUTPUT:

No handles with labels found to put in legend.

试试这个。

# plot data
p1 = plt.plot(x,y1)
plt.legend((p1[0]), (header[0]), fontsize=12, ncol=1, framealpha=0, fancybox=True)