import matplotlib.pyplot as plt x = [1, 2, 3] y1 = [2, 4, 6] y2 = [1, 3, 5] line1, = plt.plot(x, y1, label='Line 1') line2, = plt.plot(x, y2, label='Line 2') legend1 = plt.legend(handles=[line1], loc='upper left') plt.gca().add_artist(legend1) plt.legend(handles=[line2], loc='upper right') plt.show()
The first legend is created for 'Line 1' and added explicitly to the axes as an artist. Then the second legend is created for 'Line 2' and placed separately. This results in two distinct legends shown on the plot.
add_artist() when adding multiple legends in matplotlib?Matplotlib allows only one legend per axes by default. Using add_artist() adds the first legend as a fixed artist, freeing the axes to add another legend separately.
import matplotlib.pyplot as plt x = [1, 2, 3] y1 = [2, 4, 6] y2 = [1, 3, 5] plt.plot(x, y1, label='Line 1') plt.plot(x, y2, label='Line 2') plt.legend(loc='upper left') plt.legend(loc='upper right') plt.show()
Calling plt.legend() twice replaces the first legend with the second. No error occurs, but only the last legend is visible.
import matplotlib.pyplot as plt x = [1, 2, 3] y1 = [2, 4, 6] y2 = [1, 3, 5] scatter1 = plt.scatter(x, y1, color='red', marker='o', label='Red circles') scatter2 = plt.scatter(x, y2, color='blue', marker='x', label='Blue crosses') legend1 = plt.legend(handles=[scatter1], loc='upper left') plt.gca().add_artist(legend1) plt.legend(handles=[scatter2], loc='upper right') plt.show()
Each scatter plot is assigned a legend handle. The first legend is added as an artist, allowing the second legend to be added separately. This shows two distinct legends with different colors and markers.
import matplotlib.pyplot as plt import numpy as np labels = ['A', 'B', 'C'] men_2019 = [5, 7, 6] women_2019 = [6, 9, 5] men_2020 = [7, 8, 7] women_2020 = [8, 10, 6] x = np.arange(len(labels)) width = 0.2 fig, ax = plt.subplots() bar1 = ax.bar(x - width, men_2019, width, label='Men 2019', color='blue') bar2 = ax.bar(x, women_2019, width, label='Women 2019', color='orange') bar3 = ax.bar(x + width, men_2020, width, label='Men 2020', color='green') bar4 = ax.bar(x + 2*width, women_2020, width, label='Women 2020', color='red') # Your code to add two legends here plt.show()
Legend1 groups bars by gender using bar1 and bar2 handles. It is added as an artist to keep it fixed. Legend2 groups bars by year using bar1 and bar3 handles. This creates two separate legends for gender and year.