How to generate ternary plots in Matplotlib

Ternary illustrated

I found a neat script yesterday to generate ternary plots using Matplotlib. Ternary diagrams are a simple way of visualizing data set in barycentric coordinates (a close cousin of triangular area coordinates)1. If you are not sure what to make of the plot below, the Wikipedia has a nice explanation about how to interpret ternary plots.

The tool to create ternary graphs using Python and Matplotlib is wxTernary.py and is available via Sourceforge2. I gave it a try and here is my report (running on the Enthought Python distribution).

All you have to do is load the data via the csv file, formatted like the following.

Ternary plot data

Var1-Var3 are the three barycentric coordinates, and each point to plot (Midpoint, Var1high-Var3high) possess a mixture of those three components (which must sum to 1). Thus, Var2high has a higher “concentration” of Var2, so its point should show up closer to the Var2 vertex of the triangle. Midpoint possesses equal parts Var1-Var3, so it should be plotted at the centroid of the triangle.

When I ran the script, here is the ternary plot generated:

Ternary plot

Awesome. It really couldn’t get much easier. There are simple flags in the code for generating contours, a legend, and other options.

If Excel is more your cup of tea, Will Vaughn provides a nice template for generating ternary plots using Excel.

  1. I used barycentric coordinates once in a consulting job which involved mapping a point within a triangulation of a photograph onto a cylindrical space (for a real estate virtual tour software). I picked up this tool in a finite element course—proof that you never know when what you’re learning will come in handy. 

  2. I saved a copy of the wxTernary.py source directory, so if you are reading this sometime in the future and the code is no longer available on Sourceforge, send me an email and I’ll give you the code. 

You can read more about me, follow me on Twitter, subscribe to this blog by RSS or email, and find many more posts in the archives.