Search code examples
pythontriangulationdelaunay

Triangulation method to plot a density map in Python


I have a file with the coordinates (x,y) of a set of points and I am using the triangulation method to generate a net of triangles representative of a surface. The triangulation consist of an unstructured triangular grid consisting of n points and n tri triangles.

PLOTTING DATA FROM A CSV FILE:

from matplotlib import pyplot as plt
from pandas import DataFrame
from matplotlib import style

df = DataFrame.from_csv('d:\Users\Raquel\Desktop/test.csv', header=0,
                    sep=';')  # unpact values into x and y using pandas to      load my csv file

style.use('ggplot')

I use this triangular grid to be able to calculate the density (1/surface) and then plot a density map.

PLOTTING THE DENSITY MAP BY THE TRIANGULATION METHOD

import numpy as np
from matplotlib.pyplot import (tripcolor, triplot, scatter,
show, title, savefig, colorbar)
from matplotlib.tri import Triangulation, TriAnalyzer

# Coordinates
x = df['x'].values
y = df['y'].values

# Triangulation
tri = Triangulation(x, y)

# Coordinates of the edges
ii1, ii2, ii3 = tri.triangles.T
x1 = x[ii1] ; y1 = y[ii1]
x2 = x[ii2] ; y2 = y[ii2]
x3 = x[ii3] ; y3 = y[ii3]

# Surfaces
surf = 0.5*np.abs((x2-x1)*(y3-y1)-(x3-x1)*(y2-y1))

# Density
dens = 1.0/(surf*3) # 3 points per triangle

# Plot
xd = (x1+x2+x3)*1.0/3.
yd = (y1+y2+y3)*1.0/3.


tripcolor(xd, yd, dens, cmap='cool')
colorbar()
title('Density Map')
savefig('density.png')
show()

The map is not a good representation of the density of my points and I don't know how to improve it... Is there something wrong with the code?

NOTE: here is the image of my density map: http://postimg.org/image/3y1g90nwd/c8d2af55/

here is the original image: http://postimg.org/image/lqn1b8lmx/6dca1266/


Solution

  • Instead of using triangulation, it would make more sense to use some density estimation technique, e.g.

    Gaussian Kernel Density estimation with scipy

    Fundamentally (at first glance), it seems you're treating all the triangles as equal contributions to the density, so points that are very far away have equal contribution to the surface density. If you chose a simple threshold on distance to discard edges of large triangles, you could do it that way, so you're not connecting points at arbitrarily far distances away from each other. Or if you use a proper density estimation technique, then you'll get much better and more natural results.