Удалить строку через маркер в легенде matplotlib
У меня есть график matplotlib
, созданный с помощью следующего кода:
import matplotlib.pyplot as pyplot
Fig, ax = pyplot.subplots()
for i, (mark, color) in enumerate(zip(
['s', 'o', 'D', 'v'], ['r', 'g', 'b', 'purple'])):
ax.plot(i+1, i+1, color=color,
marker=mark,
markerfacecolor='None',
markeredgecolor=color,
label=i)
ax.set_xlim(0,5)
ax.set_ylim(0,5)
ax.legend()
с этим как сгенерированная цифра:
![matplotlib generated figure]()
Мне не нравятся строки через маркеры в легенде. Как я могу избавиться от них?
Ответы
Ответ 1
Вы можете указать linestyle="None"
как аргумент ключевого слова в команде plot:
import matplotlib.pyplot as pyplot
Fig, ax = pyplot.subplots()
for i, (mark, color) in enumerate(zip(
['s', 'o', 'D', 'v'], ['r', 'g', 'b', 'purple'])):
ax.plot(i+1, i+1, color=color,
marker=mark,
markerfacecolor='None',
markeredgecolor=color,
linestyle = 'None',
label=`i`)
ax.set_xlim(0,5)
ax.set_ylim(0,5)
ax.legend(numpoints=1)
pyplot.show()
![enter image description here]()
Поскольку вы только рисуете одиночные точки, вы не можете видеть атрибут линии, за исключением легенды.
Ответ 2
Вы можете установить rcparams
для графиков:
import matplotlib
matplotlib.rcParams['legend.handlelength'] = 0
matplotlib.rcParams['legend.numpoints'] = 1
![enter image description here]()
Все параметры легенды. * доступны как ключевые слова, если вы не хотите, чтобы этот параметр применялся глобально для всех графиков. См. matplotlib.pyplot.legend документацию и этот связанный вопрос:
настройка легенды (точки и точки разброса) в matplotlib не работает
Ответ 3
Здесь вы должны использовать рассеянную диаграмму
import matplotlib.pyplot as pyplot
Fig, ax = pyplot.subplots()
for i, (mark, color) in enumerate(zip(
['s', 'o', 'D', 'v'], ['r', 'g', 'b', 'purple'])):
ax.scatter(i+1, i+1, color=color,
marker=mark,
facecolors='none',
label=i)
ax.set_xlim(0,5)
ax.set_ylim(0,5)
ax.legend(scatterpoints=1)
pyplot.show()
Ответ 4
Чтобы просто удалить строки после создания данных:
handles, labels = ax.get_legend_handles_labels()
for h in handles: h.set_linestyle("")
ax.legend(handles, labels)