Home > Enterprise >  Remove duplicate labels from matplotlib subplot legend
Remove duplicate labels from matplotlib subplot legend

Time:12-11

I am making 2 plots on a page using matplotlib.pyplot each with twin axes. An example of the code is

import numpy as np
import matplotlib.pyplot as plt

n = 30

x = np.arange(n)
a = np.random.rand(n)
b = np.random.rand(n)
c = np.random.rand(n)
d = np.random.rand(n)

fig = plt.figure()

# ... upper plot

ax1 = fig.add_subplot(2, 1, 1)
ax2 = ax1.twinx()

ax1.step(x, a, '-', color='k', label="series 1")
ax2.step(x, b, 'o', color='r', label="series 2")

fig.legend(loc='upper right', bbox_to_anchor=(1.00, 1.00), bbox_transform=ax1.transAxes)

# ... lower plot

ax3 = fig.add_subplot(2, 1, 2)
ax4 = ax3.twinx()

ax3.step(x, c, '-', color='b', label="series 3")
ax4.step(x, d, 'o', color='g', label="series 4")

fig.legend(loc='upper right', bbox_to_anchor=(1.00, 1.00), bbox_transform=ax3.transAxes)

The issue is that the lower plot has the labels from both the upper and lower plot eg. enter image description here

How do I remove the upper plot labels from the lower plot? Thanks in advance ...

CodePudding user response:

You can simply use ax*.legend() on each axis and the labels will show up in the correct plot. If you don't pass the loc argument to legend(), it will put it at a place it thinks best. If you want a specific position, you could specify it e.g. ax1.legend(loc="upper left").

CodePudding user response:

import numpy as np
import matplotlib.pyplot as plt

n = 30

x = np.arange(n)
a = np.random.rand(n)
b = np.random.rand(n)
c = np.random.rand(n)
d = np.random.rand(n)

fig = plt.figure()

# ... upper plot

ax1 = fig.add_subplot(2, 1, 1)
ax2 = ax1.twinx()

ax1.step(x, a, '-', color='k', label="series 1")
ax2.step(x, b, 'o', color='r', label="series 2")

ax1.legend(loc='upper right', bbox_to_anchor=(1, 1), bbox_transform=ax1.transAxes)
ax2.legend(loc='upper right', bbox_to_anchor=(1, 0.8), bbox_transform=ax2.transAxes)

# ... lower plot

ax3 = fig.add_subplot(2, 1, 2)
ax4 = ax3.twinx()

ax3.step(x, c, '-', color='b', label="series 3")
ax4.step(x, d, 'o', color='g', label="series 4")

ax3.legend(loc='upper right', bbox_to_anchor=(1.00, 1.00), bbox_transform=ax3.transAxes)
ax4.legend(loc='upper right', bbox_to_anchor=(1.00, 0.8), bbox_transform=ax4.transAxes)

plt.show()

enter image description here I changed my code again and hope this will help you. Take a look at this link and if it will solve your question, please make it as answered and vote up for bounty.

  • Related