0

Using matplotlib, I have a figure with subplots. Each subplot is a heatmap generated from a separate numpy array. I want to print a separate legend for each subplot. How do I do that?

In a way, my requirement is the opposite of this question: matplotlib - Legend in separate subplot

Thanks to JohanC for the suggestion. I have two requirements: one is about adding a separate legend to each subplot and also, the legend should correspond to a heatmap. On further search, it looks like the keyword to get a solution is colorbar and the following code works for me. It is based on:

matplotlib colorbar in each subplot https://matplotlib.org/examples/pylab_examples/custom_cmap.html

import matplotlib.pyplot as plt
import numpy as np

fig, axs = plt.subplots(3)

for i_ax in range(3):
    i_arr = np.random.rand(2, 2)

    im = axs[i_ax].imshow(i_arr)
    fig.colorbar(im, ax=axs[i_ax])
    # axs[i_ax].legend(loc="right")

fig.savefig('mpl_scratch.png')
Hari
  • 1,561
  • 4
  • 17
  • 26
  • 2
    You might want to add some code to [reproduce your problem](https://stackoverflow.com/help/minimal-reproducible-example) and explain what you mean by a legend for a heatmap. Having a legend for each subplot is the default behavior. Just call `ax[i].legend(...)` for each subplot where you want a legend. – JohanC Apr 25 '20 at 21:57
  • See [this post](https://stackoverflow.com/questions/31726643/how-do-i-get-multiple-subplots-in-matplotlib) about creating subplots. – JohanC Apr 25 '20 at 22:06

0 Answers0