1

I'm trying to create a legend that will have both lines and scatter plots in it. Below is what I'm getting. enter image description here

What I would like is the lines to be present in the legend (preferably) above the Model text. Also if possible all one X. Below is the code that I'm working with.

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

fig = plt.figure()

accuracy_line = plt.plot([1, 2, 3], [31,32,35], linewidth=2.0, 
label='Accuracy')
oov_line = plt.plot([1, 2, 3], [38,35,31], linewidth=2.0, label="OOV")
plt.axis([0.5, 3.5, 30, 40])
plt.xlabel('label', fontsize=14, color='Black')
plt.title("title")
plt.setp(accuracy_line, 'color', 'g', 'linewidth', 2.0)
plt.setp(oov_line, 'color', 'r', 'linewidth', 2.0)
no_lm = plt.scatter(1, 31, marker='x', s=100, linewidth=4.0, color='k')
add_corp = plt.scatter(2, 32, marker='x', s=100, linewidth=4.0, color='b')
syn_data = plt.scatter(3, 35, marker='x', s=100, linewidth=4.0, color='c')

plt.legend([accuracy_line, oov_line, no_lm, add_corp, syn_data], ['Accuracy', 'OOVs', 'Model 1', 'Model 2', 'Model 3'])
plt.show()

I've tried a few other things I've found here but I can't get it to come out.

user2743
  • 1,423
  • 3
  • 22
  • 34

1 Answers1

2

The issue with multiple Xs in the legends is weird, it's not showing that for me, I'm using matplotlib 2.0.0 and Python 3.5.1.

To get the lines legend you just need to access your plot's first index, by modifying the legend line to:

plt.legend([accuracy_line[0], oov_line[0], no_lm, add_corp, syn_data], ['Accuracy', 'OOVs', 'Model 1', 'Model 2', 'Model 3'])

Vinícius Figueiredo
  • 6,300
  • 3
  • 25
  • 44
  • 1
    The issue of several scatterpoints appearing in the legend is due to an older version of matplotlib. Newer version only use one point by default. [This question](https://stackoverflow.com/questions/6099799/how-to-create-a-scatter-plot-legend-with-only-one-symbol-for-each-label) shows how to set the number of legend points. – ImportanceOfBeingErnest Jul 13 '17 at 09:34