Search code examples
pythonmatplotliblegend-properties

Align the legend labels and handles for a combined line and scatter plot


I have this MRE:

import matplotlib.pyplot as plt
import numpy as np


for i in range(6):
    plt.plot(np.linspace(0,1), np.linspace(0,1)**(i+1), label=f'{i}')

for i in [0,2,4]:
    plt.scatter(np.linspace(0,1), np.linspace(0,1)**(i+1), label=f'{i}')
    
plt.legend(ncol=2)

Which produces:

I would like to align the entry of the scatter plot with the corresponding line plot.

The end result would be:

line0   scatter0
line1 
line2   scatter2
line3
line4   scatter4
line5

Is this possible in matplotlib?


Solution

  • To achieve this, you can add a dummy scatter plot (white with no label) inside the second FOR loop. This will add a blank legend entry after each of the scatter legend entry. Updated code below...

    for i in range(6):
        plt.plot(np.linspace(0,1), np.linspace(0,1)**(i+1), label=f'{i}')
    for i in [0,2,4]:
        plt.scatter(np.linspace(0,1), np.linspace(0,1)**(i+1), label=f'{i}')
        # Add empty scatter entry
        plt.scatter(np.zeros(1), np.zeros([1]), color='w', alpha=0, label=' ')
        
    plt.legend(ncol=2)
    

    enter image description here