user12265710
user12265710

Reputation: 89

Superimposing plot over errorbars in matplotlib

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

Upvotes: 1

Views: 321

Answers (2)

tdy
tdy

Reputation: 41327

Use plt.plot for the black lines, but just adjust the zorder:

  • Either pull the black lines above with zorder > 2

    for t, b, std, label in zip(T_arrays, B_arrays, STD_arrays, labels):
        plt.errorbar(t, b, std, linestyle='None', marker='^', label=label)
        plt.plot(t, b, color='k', zorder=3)
        #                         ^^^^^^^^
    
  • Or push the error bars below with zorder < 2

    for t, b, std, label in zip(T_arrays, B_arrays, STD_arrays, labels):
        plt.errorbar(t, b, std, linestyle='None', marker='^', label=label, zorder=1)
        plt.plot(t, b, color='k')
        #                                                                  ^^^^^^^^
    

The key value here is 2 because all lines (including error bars) have a default zorder of 2:

Type Default zorder
Images 0
Patches 1
Lines 2
Major ticks 2.01
Text 3
Legend 5

Upvotes: 1

user12265710
user12265710

Reputation: 89

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

Upvotes: 0

Related Questions