user2743
user2743

Reputation: 1513

Trying to create a legend with both scatter and line in Matplotlib

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.

Upvotes: 1

Views: 5265

Answers (1)

Vinícius Figueiredo
Vinícius Figueiredo

Reputation: 6508

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'])

Upvotes: 2

Related Questions