Aomine Aomine - 4 months ago 21
Python Question

Python - Plotting from data file with errorbars?

I've got a data file (data.txt) that has 6 columns:
Column 1 and 4 are the x and y data with column 2 and 3 being the (unsymmetrical) error bars for column 1 and columns 4 and 5 being the (unsymmetrical) error bars for column 6:

100 0.77 1.22 3 0.11 0.55
125 0.28 1.29 8 0.15 0.53
150 0.43 1.11 14 0.10 0.44
175 0.33 1.01 22 0.18 0.49
200 0.84 1.33 34 0.11 0.48


What I want to plot this. I know I need to use

import numpy as np
import matplotlib.pyplot as plt

plt.plotfile(......)

plt.show()


The bit in between the parenthesis in plotfile is where I'm not sure how to relate these error bars to the columns (as well as anything else I missed).

Answer

Using numpy.loadtxt works perfectly:

import numpy as np
import matplotlib.pyplot as plt

data = np.loadtxt("data.txt")
x = data[:, 0]
y = data[:, 3]
# errorbar expects array of shape 2xN and not Nx2 (N = len(x)) for xerr and yerr
xe = data[:, 1:3].T
ye= data[:, 4:].T

plt.errorbar(x, y, xerr=xe, yerr=ye, fmt=".-")

# if you want a log plot:
plt.xscale("log")
plt.yscale("log")

plt.show()