Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib tripcolor bug?

I want to use tripcolor from matplotlib.pyplot to view the colored contours of some of my data.

The data is extracted from an XY plane at z=cst using Paraview. I directly export the data in csv from Paraview which triangulates the plane for me.

The problem is that depending on the plane position (ie the mesh) tripcolor gives me sometimes good or bad results.

Here is a simple example code and results to illustrate it:

Code

import matplotlib.pyplot as plt
import numpy as np

p,u,v,w,x,y,z  = np.loadtxt('./bad.csv',delimiter=',',skiprows=1,usecols=(0,1,2,3,4,5,6),unpack=True)

NbLevels = 256

plt.figure()
plt.gca().set_aspect('equal')

plt.tripcolor(x,y,w,NbLevels,cmap=plt.cm.hot_r,edgecolor='black')

cbar = plt.colorbar()
cbar.set_label('Velocity magnitude',labelpad=10)

plt.show()

Results with tripcolor

enter image description here

Here is the file that causes the problem.

I've heard that matplotlib's tripcolor is sometimes buggy, so is it a bug or not ?

like image 251
Ragloo Avatar asked Mar 03 '26 09:03

Ragloo


1 Answers

As highlighted by @Hooked this is the normal behaviour for a Delaunay triangulation. To remove unwanted triangles you should provide your own Triangulation by passing explicitly the triangles.

This is quite easy in your case as your data is almost structured: I suggest performing a Delaunay triangulation in the plane (r, theta) then passing these triangles to the initial (x, y) arrays. You can make use of the the built-in TriAnalyzer class to remove very flat triangles from the (r, theta) triangulation (they might exists due to round-off errors).

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.tri as mtri

p,u,v,w,x,y,z  = np.loadtxt('./bad.csv',delimiter=',',skiprows=1,usecols=(0,1,2,3,4,5,6),unpack=True)

r = np.sqrt(y**2 + x**2)
tan = (y / x)
aux_tri = mtri.Triangulation(r/np.max(r), tan/np.max(tan))
triang = mtri.Triangulation(x, y, aux_tri.triangles)
triang.set_mask(mtri.TriAnalyzer(aux_tri).get_flat_tri_mask())

NbLevels = 256

plt.figure()
plt.gca().set_aspect('equal')

plt.tripcolor(triang, w, NbLevels, cmap=plt.cm.jet, edgecolor='black')

cbar = plt.colorbar()
cbar.set_label('Velocity magnitude',labelpad=10)
plt.show()

enter image description here

like image 61
GBy Avatar answered Mar 06 '26 00:03

GBy