Home > other >  Superimposing plot over errorbars in matplotlib
Superimposing plot over errorbars in matplotlib

Time:12-29

I am trying to superimpose a plot over my error bars. I have searched online and this seems to be the method to do this. I am expecting the plot to look the way it does however with thin black lines running between the thick colour lines.

plt.figure(figsize=(15, 10), dpi=80)
plt.grid(True, linewidth=0.5, color='#ff0000', linestyle='-')

for i in range(len(B_arrays)):
    plt.errorbar(T_arrays[i], B_arrays[i], STD_arrays[i], linestyle='None', marker='^', label = labels[i])
    plt.plot(T_arrays[i], B_arrays[i], color = "k")
    
plt.ylabel("B")
plt.xlabel("Time")
plt.legend(loc="upper right", prop={'size': 8})
plt.show()

enter image description here

CodePudding user response:

I found a solution, however it is not the cleanest way. I'm open to better ways to do this if the community has other approaches.

plt.figure(figsize=(15, 10), dpi=80)
plt.grid(True, linewidth=0.5, color='#ff0000', linestyle='-')

for i in range(len(B_arrays)):
    plt.errorbar(T_arrays[i], B_arrays[i], STD_arrays[i], linestyle='None', marker='^', label = labels[i])
    plt.errorbar(T_arrays[i], B_arrays[i], np.zeros(len(B_arrays[i])),color = "k")
    
plt.ylabel("B")
plt.xlabel("Time")
plt.legend(loc="upper right", prop={'size': 8})
plt.show()

enter image description here

CodePudding user response:

Use plt.plot for the black lines, but set the zorder to 3 or higher:

for i in range(len(B_arrays)):
    plt.errorbar(T_arrays[i], B_arrays[i], STD_arrays[i], linestyle='None', marker='^', label=labels[i])
    plt.plot(T_arrays[i], B_arrays[i], color='k', zorder=3)
    #                                             ^^^^^^^^

It needs to be 3 because all lines (including error bars) are 2 by default:

artist default zorder
images 0
patches 1
lines 2
major ticks 2.01
text 3
legend 5
  • Related