Luis Ramon Ramirez Rodriguez Luis Ramon Ramirez Rodriguez - 6 months ago 21
Python Question

Overlap legends in matplotlib

I'm making a linear regression and plotting the data points as well as the regression line.

The code I'm making it this way:

x = np.r_[0.,3.15,5.39,7.29,11.55,14.4,19.8,23.4,25.7]
y = np.r_[0,0.13,0.2,0.27,0.42, 0.51,0.68,0.80,0.88]
model = linear_model.LinearRegression()
X = x.reshape(-1,1)
Y = y.reshape(-1,1)
model.fit(X,Y)
plt.plot(x,y,'*')
plt.plot(x,model.predict(X))
plt.legend('experimental values')
plt.show()


enter image description here

I want to make the legend to have both, the line and the dot as 'experimental values '

Similar as this image:

enter image description here

Answer

The following seems to work:

import matplotlib.pyplot as plt
from sklearn import linear_model

# Funky hack to change the number of "stars" in the legend to be 1,
# I feel like there has to be a better way to do this...
from pylab import *
rcParams['legend.numpoints'] = 1

x = np.r_[0.,3.15,5.39,7.29,11.55,14.4,19.8,23.4,25.7]
y = np.r_[0,0.13,0.2,0.27,0.42, 0.51,0.68,0.80,0.88]
model = linear_model.LinearRegression()
X = x.reshape(-1,1)
Y = y.reshape(-1,1)
model.fit(X,Y)

blue_dot, = plt.plot(x,y, '*')
green_line, = plt.plot(x,model.predict(X), 'g')

plt.legend([(blue_dot, green_line)], ["DesiredKey"], loc='upper center')
plt.show()

Output is:

enter image description here

The trick to finding this solution was hunting through the docs (per usual), and finding an example of the HandlerTuple class. See here. Hope this is what you wanted, let me know if I missed something!

Comments