Thursday, June 21, 2012

Importing data into Python for a 2D plot

Yay!  I'm learning some Python! (For Family Guy fans this is in Peter's voice when Lois lets him take his cage of parrots on a trip and he says, Yay, you're letting me be myself!).

So I needed to load a small sample of data (about 7 data points) into a 2D graph in Python.  After awhile of searching and trial and error, I finally found a solution.

First, I had to figure out how to get Python to read the data and read it in a proper format or format that I needed for use.  Basically, a 2x2 array for x and y values.

At first I thought plotfile under matplolib under cbook and using fname and get_sample_data would work.

I also tried the csv package/module/library or whatever the proper term is in Python and its reader function.

I did get this to display my data in a table
import csv
reader = csv.reader(open("some.csv", "rb"))
for row in reader:
    print row
Here is a screenshot:

However, I found loadtxt and upack=True but ended up using NumPy's genfromtxt which seems like they accomplish essentialyl the same thing, to load my data into a 2x2 matrix or array.

CSV stands for Comma Separated Value
The so-called CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. There is no “CSV standard”, so the format is operationally defined by the many applications which read and write it. The lack of a standard means that subtle differences often exist in the data produced and consumed by different applications. These differences can make it annoying to process CSV files from multiple sources. Still, while the delimiters and quoting characters vary, the overall format is similar enough that it is possible to write a single module which can efficiently manipulate such data, hiding the details of reading and writing the data from the programmer. The csv module implements classes to read and write tabular data in CSV format. It allows programmers to say, “write this data in the format preferred by Excel,” or “read data from this file which was generated by Excel,” without knowing the precise details of the CSV format used by Excel. Programmers can also describe the CSV formats understood by other applications or define their own special-purpose CSV formats.
My code is:

import numpy as np
import matplotlib.pyplot as plt

x, y = np.genfromtxt('1952_Kelsall_ax_vel_ser_I_first_z_loc_closeup_2.csv', delimiter = ',', unpack=True)
y = np.multiply(1.62, y)
y = np.divide(y, 2885)

plt.plot(x, y, 'o')

So I imported my data into x and y using unpack=True to ensure that the data went into its own column. I then did some scaling using NumPy's multiply and divide. Then simple plotted onto a 2D graph using 'o' for data points only.


Here is a NumPy tutorial and reference:

Tentative NumPy Tutorial

Numpy Example List

No comments:

Post a Comment