Setting different colors for markers and lines in matplotlib and show them in legend

Viewed 709

I would like to create a plot, consisting of lines and markers, but using different colors for both. My approach was to use two averlapped plots:

#!/usr/bin/env python3
import matplotlib.pyplot as plt
fig,ax1 = plt.subplots()
x=[0,1,2,3]
y=[10,20,40,80]
ax1.plot(x, y,color='#FF0000', alpha=0.5, linewidth=2.2,label='Example line',zorder=9)
ax1.scatter(x, y ,marker='o',s=80,color='black',alpha=1,label='Example marker',zorder=10) 

ax1.set_ylim([0,150])
ax1.set_xlim([0,5])
ax1.legend(loc='upper right')
plt.show()
plt.close()

Output:

Figure output

The problem here is that, naturally, line (----) and marker (X) are showed separately in legend.

Would you know a way to show both marker and line together in legend, that is to say, in a composed line and marker (---X---) label?

1 Answers

Perhaps just specify your marker attributes in the first plot call... e.g.

ax1.plot(x, y,color='#FF0000', linewidth=2.2, label='Example line',
          marker='o', mfc='black', mec='black', ms=10)

enter image description here

Related