Matplotlib: How to combine scatter and line plot to one legend entry

28H4 :

I draw my data points with ax.scatter() and connect the data points with a fit using ax.plot().

How do I create a common entry in the legend that combines the marker for the data point with the line of the fit? I want to get a legend entry as I would get it for ax.plot(x, y, '-o', label = 'abc').

I have created the following minimal example:

import matplotlib.pyplot as plt
import numpy as np

x_scatter = np.linspace(0,10,10)
x_line = np.linspace(0,10,100)

fig, ax = plt.subplots()

for i in range(5):
    ax.scatter(x_scatter, np.sin(x_scatter) + i, label = i)
    ax.plot(x_line, np.sin(x_line)+i)

plt.legend(loc='best')
plt.show()
Julien :

This 'hack' should work:

import matplotlib.pyplot as plt
import numpy as np

x_scatter = np.linspace(0,10,10)
x_line = np.linspace(0,10,100)

fig, ax = plt.subplots()
prop = ax._get_lines.prop_cycler

for i in range(5):
    color = next(prop)['color']
    ax.scatter(x_scatter, np.sin(x_scatter) + i, color=color)
    ax.plot(x_line, np.sin(x_line)+i, color=color)
    ax.plot([], [], '-o', color=color, label = i)

plt.legend(loc='best')
plt.show()

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=23726&siteId=1