Search code examples
pythonploterrorbar

Why my errorbar are shown with many strange lines?


This is my code and when I run my grafic is this: enter image description here I don't know how to solve it. Just when I plot many values it happens. My file is this: https://drive.google.com/file/d/1gfljbTr82K5lLKRa7BVbs5JUmqtaZsp1/view?usp=sharing

I'm trying to plot errorbar of each value.

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

df = pd.read_csv('C:/Users/LENOVO/Downloads/PN_ART.txt', sep=" ", header=0)
#oxígeno
O3art = df.loc[:, 'O3'] 
eO3art = df.loc[:, 'eO3'] 
#Nitrógeno
N2art = df.loc[:, 'N2'] 
eN2art = df.loc[:, 'eN2'] 
#Hidrógeno
Halphart = df.loc[:, 'Halpha'] 
eHalphart = df.loc[:, 'eHalpha'] 
eHbetart = df.loc[:, 'eHbeta'] 

Y = np.log(O3art)
X = np.log(N2art/Halphart)

xe = eN2art + eHalphart
ye = eO3art + eHbetart

plt.plot(X, Y, 'go')
plt.errorbar(X, Y, xerr=xe, yerr=ye, color='k')

Solution

  • Matplotlib defaults to draw lines between succesive points. If you plot several points, that are not ordered along the x-axis, this will produce the strange zigzag lines you observe in your plot.

    One solution would be to sort the data points by their x values. Another one would be to tell matplotlib to not draw the lines. This can be done by passing a

    linestyle=''
    

    to the plot commands. Usually if you happen to have this problem, the lines between the points don't have a meaning anyway, so it is also better to not draw them from a scientific point of view.

    By the way you can (and should combine the plot() and errorbar() call into one errorbar() call e.g. like this

    plt.errorbar(X, Y, xerr=xe, yerr=ye, marker='o', color='g', linestyle='', ecolor='k')
    

    You can find the meaning of the arguments and additional options in the documentation of the errorbar() function.