我只想显示图例中的标记(我不想显示标记中间的线条)。我不想从图中删除线条,只在图例中删除。
我从这个thread尝试了下面的代码:
handles, labels = ax.get_legend_handles_labels()
for h in handles: h.set_linestyle("")
ax.legend(handles, labels)
它也从图中删除了线条。
有办法吗?
您可以使用
matplotlib.rcParams['legend.handlelength'] = 0
,而不是两次绘制图表,这可能会带来一些开销。这是一个全局参数,这意味着它会在事后影响所有其他图表。
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
matplotlib.rcParams['legend.handlelength'] = 0
x = np.linspace(-np.pi/2, np.pi/2, 31)
y = np.cos(x)**3
# 1) remove points where y > 0.7
x2 = x[y <= 0.7]
y2 = y[y <= 0.7]
# 2) mask points where y > 0.7
y3 = np.ma.masked_where(y > 0.7, y)
# 3) set to NaN where y > 0.7
y4 = y.copy()
y4[y3 > 0.7] = np.nan
plt.plot(x*0.1, y, 'o-', color='lightgrey', label='No mask')
plt.plot(x2*0.4, y2, 'o-', label='Points removed')
plt.plot(x*0.7, y3, 'o-', label='Masked values')
plt.plot(x*1.0, y4, 'o-', label='NaN values')
plt.legend()
plt.title('Masked and NaN data')
plt.show()
如果你只想将它用于一个图,你可以将负责图的代码包装成:
with plt.rc_context({"legend.handlelength": 0,}):
更新中... 有一个特定的选项可以做到这一点......
import numpy as np
import matplotlib.pyplot as plt
# dummy data
x = np.arange(10)
y1 = 2*x
y2 = 3*x
fig, ax = plt.subplots()
line1, = ax.plot(x, y1, c='blue', marker='x')
line2, = ax.plot(x, y2, c='red', marker='o')
ax.legend([line1, line2], ['data1', 'data2'], handlelength=0.)
plt.show()