Search code examples
pythonfor-loopmatplotliberrorbar

Matplotlib error bar using a for loop (for different colors)


I would like to plot a set of error bars with different colors. Also different colours for my data points.

At the moment I am using:

colours = ['r','b','g','k','m']
labels = ['200Mpc','300Mpc','340Mpc','400Mpc','450Mpc']

fig2 = plt.figure(figsize=(7,5))
ax3 = fig2.add_subplot(111)
for a,b,c,d,e,f in zip(r0_array,gamma_array,r0_error,gamma_error,colours,labels):
    ax3.scatter(r0_array,gamma_array,c=e,label=f)
    ax3.errorbar(r0_array,gamma_array,xerr=c,yerr=d,fmt='o',color=e)
ax3.set_xlabel('$r_{0}$',fontsize=14)
ax3.set_ylabel(r'$\gamma$',fontsize=14)
ax3.legend(loc='best')
fig2.show()

Which results in a figure with the errorbars and colours being overplotted.

enter image description here

I can see that the for loop is being run 5 times again, as I can see all the colours, but I don't see why this is happening!


Solution

  • I figured out the very silly mistake I was making!!

    After the for loop, each value, i.e. a,b,c,d,e,f take the values inside the arrays r0_array,gamma_array etc..

    Instead of calling a,b,c, and d in scatter, I am calling the entire array r0_array, gamma_array,etc.. each time.

    for a,b,c,d,e,f in zip(r0_array,gamma_array,r0_error,gamma_error,colours,labels):
            ax3.scatter(a,b,color=e,label=f)
            ax3.errorbar(a,b,xerr=c,yerr=d,fmt='o')
    

    fixed the issue.