No artists with labels found to put in legend. Note that artists whose label start with an underscore are ignored when legend() is called with no argument.
时间: 2023-06-12 08:02:41 浏览: 486
这个问题通常发生在使用 matplotlib 绘图时没有设置图例标签。当你在使用 `legend()` 函数时,它需要知道哪些艺术家与标签相关联。如果没有设置标签,它将无法找到相应的艺术家来创建图例。
要解决这个问题,你需要在绘制图形时为每个艺术家设置标签。例如,如果你在绘制折线图时使用了 `plot()` 函数,则可以在该函数中设置标签参数,如下所示:
```python
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y, label='line 1') # 设置标签
plt.legend() # 显示图例
plt.show()
```
这将为折线图创建一个标签为 "line 1" 的图例。你还可以在 `legend()` 函数中直接设置标签,如下所示:
```python
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y) # 没有设置标签
plt.legend(['line 1']) # 直接设置标签
plt.show()
```
这将创建一个标签为 "line 1" 的图例,因为我们在 `legend()` 函数中直接设置了标签。
相关问题
报错:No artists with labels found to put in legend Note that artists whose label start with an underscore are ignored when legend() is called with
这个错误一般是因为在创建图例时没有正确指定图例的标签。通常情况下,我们需要在创建图形对象时指定标签,然后在创建图例时使用这些标签。例如:
```python
import matplotlib.pyplot as plt
# 创建图形对象,并指定标签
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y, label='data')
# 创建图例,并显示
plt.legend()
plt.show()
```
如果在创建图形对象时没有指定标签,或者标签以下划线开头,那么在创建图例时就会出现上述错误。因此,确保在创建图形对象时正确指定标签,或者在创建图例时手动指定标签,即可解决这个问题。
No artists with labels found to put in legend.
这个错误通常发生在绘制图例时,因为没有找到要在图例中显示的标签。可能的原因是您没有指定标签,或者标签没有正确地与数据对应。
通常,你需要在绘制图表时指定标签。例如,如果你使用 matplotlib 绘制散点图,你可以这样指定标签:
```python
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [10, 20, 30, 40]
labels = ['A', 'B', 'C', 'D']
plt.scatter(x, y, label='my data')
plt.legend()
```
在这个例子中,我们使用 `label` 参数指定了标签。当我们调用 `plt.legend()` 时,matplotlib 将自动在图例中显示这个标签。
如果你的数据是 pandas DataFrame,你可以使用列名作为标签。例如:
```python
import pandas as pd
import matplotlib.pyplot as plt
data = pd.DataFrame({
'x': [1, 2, 3, 4],
'y': [10, 20, 30, 40],
'label': ['A', 'B', 'C', 'D']
})
plt.scatter(data['x'], data['y'], label=data['label'])
plt.legend()
```
在这个例子中,我们将数据存储在一个 pandas DataFrame 中,并使用 DataFrame 的列名作为标签。这样,当我们调用 `plt.legend()` 时,matplotlib 将自动使用列名作为标签。