Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to have a figure legend and a subplot legend in python?

I would like to plot some data in subplots and I would like to have a legend for the overall figure but also a legend for one of the subplots, where the labels of the subplot should not appear in the figure label.

Here is an example:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(2, 1)

a = np.random.rand(5)
b = np.random.rand(5)
a1 = np.append(a, 0.5)
b1 = np.append(b, 0.5)

ax[0].plot(a, color='red', label='one')
ax[0].plot(b, color='blue', label='two')

ax[1].plot(a1, color='red', label='one appended')
ax[1].plot(b1, color='blue', label='two appended')
ax[1].legend()

fig.legend()

plt.show()

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I get rid of the ‘one appended’ and ‘two appended’ labels in the figure legend?

Thanks for your help!

>Solution :

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(2, 1)

a = np.random.rand(5)
b = np.random.rand(5)
a1 = np.append(a, 0.5)
b1 = np.append(b, 0.5)

ax[0].plot(a, color='red')
ax[0].plot(b, color='blue', label='two')
ax[0].legend(['one','two'])

ax[1].plot(a1, color='red')
ax[1].plot(b1, color='blue')
ax[1].legend(['one appended', 'two appended'])

fig.legend(["one whole", "two whole"])

plt.show()

I don’t know if this helps you.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading