0

I have the following code:

x1 = np.linspace(0, 5, 10)
y1 = x1 + np.random.randn(10)
y2 = x1 + np.random.randn(10)

x2 = np.linspace(0, 5, 10)
y3 = x2 + np.random.randn(10)
y4 = x2 + np.random.randn(10)

x3 = np.linspace(0, 5, 10)
y5 = x3 + np.random.randn(10)
y6 = x3 + np.random.randn(10)

x4 = np.linspace(0, 5, 10)
y7 = x4 + np.random.randn(10)
y8 = x4 + np.random.randn(10)

# Set up a figure with 2 rows and 2 columns of subplots
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)

x = [i for i in range(10,101,10)]



# Plot multiple line charts on each subplot
l1, = ax1.plot(x1, y1, 'o-')
l2, = ax1.plot(x1, y2, '^-')
ax1.legend((l1, l2), ('Line 1', 'Line 2'))

l3, = ax2.plot(x2, y3, 's-')
l4, = ax2.plot(x2, y4, 'd-')
ax2.legend((l3, l4), ('Line 3', 'Line 4'))

l5, = ax3.plot(x3, y5, 'x-')
l6, = ax3.plot(x3, y6, '+-')
ax3.legend((l5, l6), ('Line 5', 'Line 6'))

l7, = ax4.plot(x4, y7, '*-')
l8, = ax4.plot(x4, y8, 'p-')
ax4.legend((l7, l8), ('Line 7', 'Line 8'))

# Set the x- and y-limits and labels for each subplot
ax1.set_xlim([0, 5])
ax1.set_ylim([0, 10])
ax1.set_xlabel('X1')
ax1.set_ylabel('Y1')
ax1.set_title('Subplot 1')

ax2.set_xlim([0, 5])
ax2.set_ylim([0, 10])
ax2.set_xlabel('X2')
ax2.set_ylabel('Y2')
ax2.set_title('Subplot 2')

ax3.set_xlim([0, 5])
ax3.set_ylim([0, 10])
ax3.set_xlabel('X3')
ax3.set_ylabel('Y3')

Which yields:

enter image description here

With my actual datasets, the lines with the same color are the same. Hence, I only need one legend on the side of the four subplots. How can I do this?

Emil
  • 1,531
  • 3
  • 22
  • 47
  • 3
    Does this answer your question? [How do I make a single legend for many subplots?](https://stackoverflow.com/questions/9834452/how-do-i-make-a-single-legend-for-many-subplots) – Woodford Jan 06 '23 at 23:56
  • Thanks! I have added `handles, labels = ax1.get_legend_handles_labels() fig.legend(handles, labels, loc='upper center')` underneath my code. However, this does not yield the desired result. How should I use this? – Emil Jan 07 '23 at 00:01
  • 1
    Note that for items to appear in r a legend, you need to add labels, e.g. `ax1.plot(x1, y1, 'o-', label='Line 1')`. `ax1.get_legend_handles_labels()` will grab all handles (being `l1`and `l2`) and their labels. If you really want to work without `label=`, you can follow your approach with `fig.legend((l1, l2), ('Line 1', 'Line 2'))`. – JohanC Jan 07 '23 at 01:20

0 Answers0