Matplotlib Reading information from a file and plotting

How to read and plot from a file in Python




Now that you have learned how simple it is to plot a simple graph, you might be wanting to plot from a file. The following method of plotting from a file is not the most efficient, but it is simple and easy to understand. If you already know more advanced I/O methods, feel free to use them instead of thee simple ones used here.

Let us just use some simple data like:

Save this as SampleData.txt in the same directory as your current Python script.

1,5
2,2
3,7
4,9
5,3
6,2
7,8
8,4
9,1   
	  

Now, we can do the following:

import matplotlib.pyplot as plt

x = []
y = []

readFile = open('SampleData.txt','r')
sepFile = readFile.read().split('\n')
readFile.close()

for plotPair in sepFile:
    xAndY = plotPair.split(',')
    x.append(int(xAndY[0]))
    y.append(int(xAndY[1]))

plt.plot(x,y)
plt.title('Matplotlib Graph')
plt.xlabel('x axis label')
plt.ylabel('y axis label')

plt.show()   
	  

Fore more tutorials, head to the