# 3.3.5 Creating a Contour Plot from Matrix

## Introduction

In this example, we will scan the contents of an ASCII file, and pick up the numeric values in sequence, then save them in a 2D array by Python. The 2D array will be appended to a Matrix by the SetData function in the PyOrigin class.

You can follow the steps below to create a contour graph by using the existing Matrix:

1. Create new GraphPage using the specified template by CreatePage
2. Get the first layer of the Graphpage.
3. Create a new data range and add the matrix into the range.
4. Plot the matrix as contour graph by using AddPlot

## Examples

# The following Python example reads data from an ASCII file
# And put data into a matrix and plot a contour from the matrix
import PyOrigin

# Get path and name of a data file in Origin's Samples folder.
originPath = PyOrigin.GetPath(PyOrigin.PATHTYPE_SYSTEM)
dataFileName = originPath + "Samples\\Matrix Conversion and Gridding\\Direct.dat"

# Read all non-empty lines from file.
dataLines = [i for i in open(dataFileName) if i[:-1]]
rowCount = len(dataLines)

# Convert each line into a list of column values.
for ii in list(range(rowCount)):
dataLines[ii] = dataLines[ii].rstrip().split("\t")
colCount = max([len(x) for x in dataLines])

# Copy strings from 'dataLines' to 'data' as float values.
# 'dataLines' is a list, each element a list of values for a row.
# 'data' is a list, each element a list of values for a column.
data = []    # list of columns
columns = [] # list of values for a single column
for ii in list(range(colCount)):
columns = [float(element[ii]) for element in dataLines]
data.append(columns)

# Create matrix page named 'Python' using template named 'Origin'.
mpName = PyOrigin.CreatePage(PyOrigin.PGTYPE_MATRIX, "MyData", "Origin", 1)
mp = PyOrigin.MatrixPages(str(mpName))

# Set matrix layer dimensions.
ml = mp.Layers(0)        # Get first matrix layer from matrix page.
ml.SetColCount(colCount) # Set number of columns in matrix layer.
ml.SetRowCount(rowCount) # Set number of rows in matrix layer.

# Set matrix layer name to file name without path.
ml.SetName(dataFileName.split("\\")[-1])

# Put imported data into matrix.
mo = ml.MatrixObjects(0) # Get first matrix object from matrix layer.
mo.SetData(data, 0, 0)   # Set data in matrix object.

# Create graph page named 'MyGraph' using template named 'Contour'.
gpName = PyOrigin.CreatePage(PyOrigin.PGTYPE_GRAPH, "MyGraph", "Contour", 1)
gp = PyOrigin.Pages(str(gpName)) # Get graph page by name
gl = gp.Layers(0)                # Get first graph layer from graph page.
rng = PyOrigin.NewDataRange()    # Create data range.
dp = gl.AddPlot(rng, 226) # Add new plot to graph layer using data range.