python - matplotlib 图例 : I see everything twice

标签 python matplotlib

我有几个数据系列,每个系列都是一条无噪声理论曲线,还有一个 Nx2 噪声数据数组,我需要用图例显示这些数据。以下代码有效,但由于 Nx2 数据,我在图例中得到了两个条目...有没有办法避免这种情况?

import numpy as np
import matplotlib.pyplot as plt

t = np.arange(0,1,0.001)
td = np.arange(0,1,0.1)
td = np.atleast_2d(td).T
N = len(td)
x1 = t
x1r = td + 0.1*np.random.randn(N,2)
x2 = 2-t
x2r = 2-td + 0.1*np.random.randn(N,2)

plt.plot(t,x1,color='red')
plt.plot(td,x1r,'.',color='red',label='A')

plt.plot(t,x2,color='green')
plt.plot(td,x2r,'x',color='green',label='B')

plt.legend()

enter image description here

最佳答案

我可以通过在图例上指定句柄来解决这个问题:

import numpy as np
import matplotlib.pyplot as plt

t = np.arange(0,1,0.001)
td = np.arange(0,1,0.1)
td = np.atleast_2d(td).T
N = len(td)
x1 = t
x1r = td + 0.1*np.random.randn(N,2)
x2 = 2-t
x2r = 2-td + 0.1*np.random.randn(N,2)

plt.plot(t,x1,color='red')
red_dots,_ = plt.plot(td,x1r,'.',color='red',label='A')

plt.plot(t,x2,color='green')
green_xs,_ =plt.plot(td,x2r,'x',color='green',label='B')

plt.legend(handles=[red_dots, green_xs])
plt.show()

enter image description here

但是,我不太确定您为什么会遇到这个问题...当我对此有更多见解时会更新答案。

关于python - matplotlib 图例 : I see everything twice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48372758/

相关文章:

python - 在一长串字典中查找特定的字典

python - 使用 matplotlib/python 设置绘图轴限制时出现问题

python - 如何在 Matplotlib 上绘制两个数据点之间的水平线?

python - 在 python 图中, "1e8"相对于 y 轴意味着什么?

Python检查字典是否是其他字典的一部分

python - 使用 python 获取 http 响应代码

python - Flask 和 Flask-Login 的新功能 - ImportError : No module named login

python - Pyspark Dataframe - 如何根据列数组作为输入连接列

python - 如何将数据帧每一行的观察结果绘制为线图

python - seaborn 热图上的辅助 x 轴