【问题标题】:Why is there an error regarding handles with labels in Python?为什么 Python 中带有标签的句柄会出现错误?
【发布时间】:2018-10-22 19:19:15
【问题描述】:

我正在尝试从 .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.

【问题讨论】:

  • 请显示完整的回溯
  • ax.legend()
  • 要创建图例,您需要为情节上的艺术家提供标签。即在plt.plot中使用label=参数
  • 澄清上述评论:plt.plot(x, y1 , label='something').
  • 请注意 - 此警告不再出现在 matploltib 2.1 及更高版本中

标签: python matplotlib legend handle


【解决方案1】:

试试这个。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-06
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    相关资源
    最近更新 更多