nirv85
nirv85

Reputation: 23

Reading two data sets in for one matplotlib plot

I try to plot two data sets in one plot, including errorbars. It worked perfectly fine for one data set. But in this "solution" :

from __future__ import print_function
from matplotlib import pyplot as plt
import numpy as np

f2 = open('data1.txt', 'r')
lines = f2.readlines()
f2.close()

f3 = open('data2.txt', 'r')
lines2 = f3.readlines()
f3.close()

x1 = []
y1 = []
xerr1 = []
yerr1 = []

x2 = []
y2 = []
xerr2 = []
yerr2 = []


for line in lines:
    p = line.split()
    x1.append(float(p[0]))
    y1.append(float(p[1]))
    xerr1.append(float(p[2]))
    yerr1.append(float(p[3]))

for line2 in lines2:
    k = line2.split()
    x2.append(float(k[0]))
    y2.append(float(k[1]))
    xerr2.append(float(k[2]))
    yerr2.append(float(k[3]))


xv = np.array(x1)
yv = np.array(y1)
xerror = np.array(xerr1)
yerror = np.array(yerr1)

xv2 = np.array(x2)
yv2 = np.array(y2)
xerror2 = np.array(xerr2)
yerror2 = np.array(yerr2)

fig = plt.figure()


ax1 = fig.add_subplot(111)

ax1.set_title("test", fontweight='bold')    
ax1.set_xlabel('test', fontsize=14, fontweight='bold')
ax1.set_ylabel('test', fontsize=16, fontweight='bold')
ax1.grid(True)
plt.ylim(67.2, 70.75) 
plt.xlim(-45, 30) 


plt.errorbar(xv, yv, xerr=xerror, yerr=yerror, fmt='-o', linestyle='None', color='k', marker='.')
plt.errorbar(xv2, yv2, xerr=xerror2, yerr=yerror2, fmt='-o', linestyle='None', color='k', marker='.')

plt.plot(xv, yv, marker='o', markersize='6', markeredgewidth='0', linestyle='None', linewidth=0, color='b')
plt.plot(xv2, yv2, marker='o', markersize='6', markeredgewidth='0', linestyle='None', linewidth=0, color='r')

plt.show()

I only get the error

exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
File "E:/script.py", line 39, in <module>
        x2.append(float(k[0]))
    IndexError: list index out of range

I do not see the error and need some help. Does anybody have an idea what is wrong in this way? I hope it is not too easy...

Upvotes: 2

Views: 102

Answers (2)

docmen
docmen

Reputation: 11

Your problem is that at some point k=line2.split() does not have any elements. For example, if the second file has an empty line (as it might have at the end), then the split function will give you an empty list

Upvotes: 1

agold
agold

Reputation: 6276

You probably have an empty line in for line2 in lines2:, because it gives a IndexError: list index out of range for k[0], meaning that the index 0 does not exist for k in that case. Be sure that you check that the split result is not empty.

For example:

for line2 in lines2:
    k = line2.split()
    if len(k)==0:
       #do something
    else:
       x2.append(float(k[0]))
       y2.append(float(k[1]))
       xerr2.append(float(k[2]))
       yerr2.append(float(k[3]))

The same should be done for the first for loop.

Upvotes: 1

Related Questions