2

I have a plot in which some data is represented by a scatter plot with error bars and I want to fit a curve to it. However, no matter where in the code I plot the curve, the error bars float on top of it. I want the fitted curves to display in front of the error bars because otherwise I can't see it.

Here is a simple example of the issue:

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')
ax3 = ax.twinx()
ln2 = ax3.errorbar(x,r,yerr=x,color='red',fmt='o')
ln2fit = ax3.plot(x,r-0.3,'b')

and the plot it produces:

enter image description here

There are two axes because I'm comparing two datasets.

As you can see, even though I plotted the curve above the error bars, the error bars and points still obscure the curve. What can I do to disable this?

Petra
  • 195
  • 1
  • 1
  • 10

1 Answers1

3

You can specify the zorder:

ln2 = ax3.errorbar(x,r,yerr=x,color='red',fmt='o',zorder=1)

enter image description here

If you also want to have the green line in the foreground you need to move it's axes ax to a higher zorder (default is 0) and hide the axes patch of ax so that the then underlying ax3 stays visible:

ax.set_zorder(1)
ax.patch.set_visible(False)

enter image description here

Stef
  • 28,728
  • 2
  • 24
  • 52
  • I have an additional question, if you know the answer- in my legend, the error bar label appears consistently below the curve label even when I add in the zorder parameter. Do you know how I would fix that? I'd like the order to be the data with the error bars and then the curve, as it would be with two regular curves plotted in that order. – Petra Feb 10 '21 at 16:01
  • 1
    I'm afraid it's not entirly clear to me. I guess it's best to ask a separate question, show what you have and somehow try to show the desired result. – Stef Feb 10 '21 at 16:13
  • I have asked the question here, if you have a moment to take a look: https://stackoverflow.com/questions/66141142/how-to-make-sure-the-matplotlib-legend-shows-curves-in-the-correct-order-with-er – Petra Feb 10 '21 at 16:44