Show Sidebar Hide Sidebar

Ternary Overlay in Python

How to make a scatter plot overlaid on ternary contour in Python with Plotly.

New to Plotly?

Plotly's Python library is free and open source! Get started by downloading the client and reading the primer.
You can set up Plotly to work in online or offline mode, or in jupyter notebooks.
We also have a quick-reference cheatsheet (new!) to help you get started!

Version Check

Note: Ternary Charts are available in version 1.9.10+ Run pip install plotly --upgrade to update your Plotly version

In [1]:
import plotly
plotly.__version__
Out[1]:
'1.12.1'

Load and Process Data Files

In [2]:
import plotly.plotly as py

import json

contour_raw_data = json.loads(open('contour_data.json').read())
scatter_raw_data = json.loads(open('scatter_data.json').read())
scatter_data =  scatter_raw_data['Data']

def clean_data(data_in):
    """
    Cleans data in a format which can be conveniently 
    used for drawing traces. Takes a dictionary as the 
    input, and returns a list in the following format:

    input = {'key': ['a b c']}
    output = [key, [a, b, c]]
    """
    key = data_in.keys()[0]
    data_out = [key]
    for i in data_in[key]:
        data_out.append(map(float, i.split(' ')))

    return data_out


#Example:
print clean_data({'L1': ['.03 0.5 0.47','0.4 0.5 0.1']})
['L1', [0.03, 0.5, 0.47], [0.4, 0.5, 0.1]]

Create Ternary Scatter Plot:

In [3]:
a_list = []
b_list = []
c_list = []
text = []

for raw_data in scatter_data:
    data = clean_data(raw_data)
    text.append(data[0])
    c_list.append(data[1][0])
    a_list.append(data[1][1])
    b_list.append(data[1][2])
    
trace1 = dict(type='scatterternary',
              text=text,
              a=a_list,
              b=b_list,
              c=c_list,
              mode='markers',
              marker={'symbol': 100,
                      'color': 'green',
                      'size': 10},
)

layout = {
    'title': 'Ternary Scatter Plot',
    'ternary':
        {
        'sum':1,
        'aaxis':{'title': 'X', 'min': 0.01, 'linewidth':2, 'ticks':'outside' },
        'baxis':{'title': 'W', 'min': 0.01, 'linewidth':2, 'ticks':'outside' },
        'caxis':{'title': 'S', 'min': 0.01, 'linewidth':2, 'ticks':'outside' }
    },
    'showlegend': False
}

scatter_fig = dict(data=[trace1], layout=layout)
py.iplot(scatter_fig)
Out[3]:

Create Ternary Contour Plot:

In [4]:
contour_dict = contour_raw_data['Data']

# Defining a colormap:
colors = ['#8dd3c7','#ffffb3','#bebada',
          '#fb8072','#80b1d3','#fdb462',
          '#b3de69','#fccde5','#d9d9d9',
          '#bc80bd']
colors_iterator = iter(colors)

traces = []
for raw_data in contour_dict:
    data = clean_data(raw_data)
    
    a = [inner_data[0] for inner_data in data[1:]]
    a.append(data[1][0]) # Closing the loop 
    
    b = [inner_data[1] for inner_data in data[1:]]
    b.append(data[1][1]) # Closing the loop     
    
    c = [inner_data[2] for inner_data in data[1:]]
    c.append(data[1][2]) # Closing the loop     
    
    trace = dict(
        type='scatterternary',text = data[0],
        a=a, b=b, c=c, mode='lines',
        line=dict(color='#444', shape='spline'),
        fill='toself',
        fillcolor = colors_iterator.next()
    )
    traces.append(trace)
    
layout['title'] = 'Ternary Contour Plot'
contour_fig = dict(data=traces, layout=layout)
py.iplot(contour_fig)
Out[4]:

Scatter Plot Overlaid on Contour Plot

We will change the marker symbol for the trace1 (The one used in scatter plot), so that it is distinctly visible on the contour background:

In [5]:
trace1['marker']['symbol'] = 'x'
trace1['marker']['color'] = '#4d79ff'
traces.append(trace1)

# update title:
layout['title'] = 'Scatter Plot overlaid on Ternary Contour Plot'
figure = dict(data=traces, layout=layout)
py.iplot(figure)
Out[5]:
Still need help?
Contact Us

For guaranteed 24 hour response turnarounds, upgrade to a Developer Support Plan.