# This line is only needed if you're using a jupyter notebook
# if you don't know what that is, you're probably not using one :)
# don't include it if you're only writing a script
%matplotlib inline
# This imports all the libraries we need
import matplotlib
import pylab as pl
import numpy as np
Let's create a file called mydata.txt
filename = "mydata.txt"
f = open(filename, "w")
Let's create two lists of numbers we'll write to it: x and y
x = [0, 1, 2, 3, 4, 5, 6]
y = [0, 1, 4, 9, 16, 25, 36]
writing to the file
# for every value in x and y we need to write a line
# python needs us to convert the number to a string first (str), and then add a newline character at the end
for (xvalue, yvalue) in zip(x,y):
f.write(str(xvalue) + " " + str(yvalue) + "\n")
# close the file after writing
f.close()
Now, let's open it
data = np.genfromtxt("mydata.txt")
print(data)
Let's assign names to the first and second columns
xx = data[:,0]
yy = data[:,1]
print(xx)
print(yy)
Now, let's plot it
pl.plot(xx,yy)
You can also plot it as a scatter plot
pl.scatter(xx,yy)
Let's create a figure, so that we can control how it's plotted
fig = pl.figure() # Create figure
ax = fig.add_subplot(111) # add some axes to it
# Add some labels
ax.set_xlabel("Oranges")
ax.set_ylabel("Apples")
# Tweak the color and size of the scatter points
ax.scatter(xx, yy, color='red', s=100)
# change the axes limits
ax.set_xlim(-2,9)
Save the plot as an image
fig.savefig("mydata.png")