0

I wrote a Python script that uses matplotlib twinx to combine a histogram and some line functions plot as can see in the figure. However I was not capable of combining both legends (nb of points and lines).

How can I do that? I tryed get_legend_handles_labels() to combine the hist and lines legend labels, also tryedto use fig.legend() with no success.

enter image description here

import matplotlib.pyplot as plt
import numpy


numpy.random.seed(19680801)

# example data
mu = 5000  # mean of distribution
sigma = 1500  # standard deviation of distribution
r1 = mu + sigma * numpy.random.randn(437)
sug_spec = numpy.arange(0, 10001, 100)
accuracy = sug_spec/2
precision = sug_spec/3
uncertainty = sug_spec/4

num_bins = 100
bins = numpy.arange(0, 10100, num_bins)

fig, ax = plt.subplots()

ax.set_xlabel('Surface Reflectance Truth')

# Plot lines
color = 'tab:pink'
ax.plot(bins, sug_spec, color=color)
color = 'tab:red'
ax.plot(bins, accuracy, color=color)
color = 'tab:green'
ax.plot(bins, precision, color=color)
color = 'tab:blue'
ax.plot(bins, uncertainty, color=color)

# Instantiate a second axes that shares the same x-axis
ax2 = ax.twinx()

# Order of each plot (Front, Back)
ax.set_zorder(2)
ax2.set_zorder(1)
ax.patch.set_visible(False)

# Remove scientific notation
ax2.ticklabel_format(style='plain')

# the histogram of the data
n, bins, patches = ax2.hist(r1, num_bins, edgecolor="k")

ax.legend(['suggested specs','accuracy','precision','uncertainty'], frameon=False, loc=1)
ax2.legend(['nb of points'], frameon=False, loc=5)

plt.show()
MarujoRe
  • 202
  • 1
  • 6
  • 1
    Does this answer your question? [Secondary axis with twinx(): how to add to legend?](https://stackoverflow.com/questions/5484922/secondary-axis-with-twinx-how-to-add-to-legend) Especially, [this by valued user ImportanceOfBeingEarnest](https://stackoverflow.com/a/47370214/8881141) sounds like an easy approach. – Mr. T Nov 20 '20 at 12:45
  • @Mr.T thank you for the suggestion. However apparently the suggestion works on lines but not on legend from hist. I wasn't able to show both legends using fig.legend. Also, when I use get_label() on the hist I also can't handle then as I would with lines. – MarujoRe Nov 20 '20 at 14:30
  • 1
    You don't provide the labels, that's why. Try: `ax.plot(bins, accuracy, color=color, label="accuracy")` etc. No need for `ax.legend()` and `ax2.legend()`. – Mr. T Nov 20 '20 at 14:36
  • 1
    @Mr.T It solved my problem. Thank you very much. I wasn't understanding fig.legend(), but now I do. – MarujoRe Nov 23 '20 at 13:16
  • Thank you for the feedback, MarujoRe. We are all here to learn. – Mr. T Nov 23 '20 at 13:19

0 Answers0