1
votes

Is it possible to add an entry to the legend in matplotlib without having plotted the corresponding object?

For example, I have two sets of three lines plotted on one graph. They come in pairs, so I want to plot them in corresponding colors, one of them dashed and the other solid.

import matplotlib.pyplot as plt
import numpy as np    
for i in range(1,4):
    line = plt.plot(i*np.arange(1,10), label=i)[0]
    plt.plot(-i*np.arange(1,10), ls='--', color=line.get_color(), label=-i)
plt.legend()

enter image description here

However, instead of having all six items in the legend, (solid blue 1, solid orange 2, solid green 3, dashed blue 1, dashed orange 2, dashed green 3) I'd like to have three (solid blue 1, solid orange 2, solid green 3) and then two additional entries to disambiguate dashed from solid (solid black 'positives', dashed black 'negatives').

How can I add these two entries, since I don't have the solid/dashed black lines plotted?

1
That question is exactly the topic of this official doc - JohanC

1 Answers

0
votes

I saw a customized reference on the official website from @JohanC's comment. Does it meet the intent of your question?

import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import numpy as np

fig, ax = plt.subplots()

legend_elements = [Line2D([0], [0], color='steelblue', ls='--',lw=2, label='blue'),
                   Line2D([0], [0], color='orange', ls='--',lw=2, label='orange'),
                   Line2D([0], [0], color='yellowgreen', ls='--',lw=2, label='green'),
                   Line2D([0], [0], color='k', ls='-',lw=2, label='positives'),
                   Line2D([0], [0], color='k', ls='--', lw=2, label='negatives')]

ax.legend(handles=legend_elements, loc='upper left')

for i in range(1,4):
    line = plt.plot(i*np.arange(1,10))[0]
    ax.plot(-i*np.arange(1,10), ls='--', color=line.get_color())
    
plt.show()

enter image description here