A. Robinson
A. Robinson

Reputation: 415

How to label columns of data as x and y

I am new to coding and I have been having trouble plotting some imported data. I have been using:

import numpy as np
import matplotlib as plt

np.loadtxt('file_name')

and I would receive something like this but much longer,

array([[  2.45732966e+06,   9.97563892e-01],
   [  2.45732967e+06,   9.98023085e-01],
   [  2.45732967e+06,   1.02989578e+00],
   [  2.45732967e+06,   1.00883389e+00],
   [  2.45732967e+06,   1.00354891e+00]])

From here I need to label column 1 as the X data and the second column as y but I'm not sure how that needs to be formatted to fit the syntax and to work with floats.

Upvotes: 0

Views: 107

Answers (2)

ingenium
ingenium

Reputation: 27

Something like that ?

import numpy as np
import matplotlib.pyplot as plt

a = np.array([[  2.45732966e+06,   9.97563892e-01],
   [  2.45732967e+06,   9.98023085e-01],
   [  2.45732967e+06,   1.02989578e+00],
   [  2.45732967e+06,   1.00883389e+00],
   [  2.45732967e+06,   1.00354891e+00]])

plt.plot(a[:,0],a[:,1])
plt.xlabel('x')
plt.ylabel('y')
plt.show()

Upvotes: 0

maow
maow

Reputation: 2887

Initialise matplotlib and the plotfunction

import matplotlib
import matplotlib.pyplot as plt

store your data into an array (assuming its not several Gb of data)

array = np.loadtxt('file_name')

plot it. The [:,0] can be read like a matrix element where : is all values. So this 'slices' the first (counting starts at 0!) column out of your array. In the call of plt.plot() you can also specify whether you want lines, points, color, size etc. by adding more arguments to it. There is a large documentation.

plt.plot(array[:,0], array[:,1])

Change plt to customize your plot. The following lines give you axis labels. You can also do logscale etc.

plt.xlabel('X')
plt.ylabel('Y')

Show the plot. Assuming you work in ipython called with --pylab=inside

plt.show()

If you want to save as pdf or something (taken from http://matplotlib.org/faq/howto_faq.html)

from matplotlib.backends.backend_pdf import PdfPages
pp = PdfPages('myfirstplot.pdf')
plt.savefig(pp, format='pdf')
pp.close()

Upvotes: 2

Related Questions