0

I have a dataset with error bars that I want to fit a curve to. I was having issues where the errorbars displayed over all lines regardless of the order of the code that I detailed in this question and was told the answer was to add a zorder parameter in the error bar function.

That worked well, but unfortunately the order of the labels in the legend still puts the error bars at the end (i.e. over the line):

enter image description here

Here I would want the line 'b' to be above 'b fit' in the legend in the top right, like the legend in the top left. This is my code:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib

x = np.arange(1,10)
r = np.random.random(x.size)

fig1, ax = plt.subplots()
ln1 = ax.plot(2*x,x,'g',label='a')
ln1fit = ax.plot(2*x-2,x,color='lightgreen',label='a fit')
plt.legend(loc='upper left')
ax3 = ax.twinx()
ln2 = ax3.errorbar(x,r,yerr=x,color='red',fmt='o',zorder=1,label="b")
ln2fit = ax3.plot(x,r,'b',label="b fit")
plt.legend(loc = 'upper right')

How would I fix this?

Petra
  • 195
  • 1
  • 1
  • 10
  • Does this answer your question? [How is order of items in matplotlib legend determined?](https://stackoverflow.com/questions/22263807/how-is-order-of-items-in-matplotlib-legend-determined) – Stef Feb 10 '21 at 16:51
  • I was hoping there was a simpler solution but if there isn't one I could make that work. Thank you! – Petra Feb 10 '21 at 16:53
  • if you just want to reverse, as in the example, maybe this answer is a bit simpler: https://stackoverflow.com/a/34576778/3944322 – Stef Feb 10 '21 at 16:55

0 Answers0