Hi Guys,
Today we are going to learn how to plot data with errors bars. This is often practiced in general scientific results and extremely useful. Let's see how it's done in Python. Here we go :
#importing essential libraries
import numpy as np
import matplotlib.pyplot as plt
#defining lists for data columns
x=[]
y=[]
error=[]
#opening data file in reading mode to read data in the form of lines
with open("data.dat", "r") as f:
for line in f:
row=line.split() # splitting lines to makes columns
x.append(float(row[0])) # appending column data into lists
y.append(float(row[1]))
error.append(float(row[2]))
# converting lists into numpy arrays
x=np.asarray(x)
y=np.asarray(y)
error=np.asarray(error)
# plotting the data with error bars
# Instead of plt.plot call plt.errorbar
# Options in the function remain the same. Some Addtions important options for error bars :
# ecolor : color of error bar, capsize : thickenss of error bar cap
plt.errorbar(x,y,yerr=error, color='r', ls='--', marker='o', markersize=10, markerfacecolor='b', markeredgecolor='k', ecolor='g', capsize=5, label='test_data')
# to enable grids in the plot
plt.grid(True)
# axis labels and plot titles
plt.xlabel("X axis")
plt.ylabel("Y axis")
plt.title("This is a test plot")
#Showing the plot and legend
plt.legend()
plt.show()
Input :
1 3 2.5
2 6 4.2
5 9 2.7
6 12 3.8
8 15 1.25
10 18 2.67
12 21 4.8
17 25 2.7
Output :
No comments:
Post a Comment