Search code examples
pythonplotlyvisualizationfigureternary

How to plot a ternary chart with lines using Plotly python?


I need to create a kind of "ternary" chart but instead of showing only points I need to set the lines, similar to the chart below:

enter image description here

I have created a data sample but I'm not 100% sure that this it has the correct data structure to build the chart

import pandas as pd 

dummy_data=[{"var1":0.74, "var2":.60, "var3":.78, "comp":"option1"},
            {"var1":0.8, "var2":0.75, "var3":0.72, "comp":"option2"}]

table=pd.DataFrame.from_dict(dummy_data)

I did a lot of searches but the most similar alternative I found was scatter_ternary which only plots points;

Any help will be very welcome!

Thank you in advance; Regards, Leonardo


Solution

  • I am new to this chart. I created the graph by replacing the examples in the official reference with lines. First of all, I needed four pieces of data from the start point to the end point. A->B->C->A Then the sum of the ABC points of that data must be the same. In my example, the sum is 1. After that I added the graph with as much triangular data as I needed.

    import pandas as pd 
    
    dummy_data=[
        {"var1":0.7, "var2":0.15, "var3":0.15, "comp":"option1"},
        {"var1":0.15, "var2":0.7, "var3":0.15, "comp":"option1"},
        {"var1":0.15, "var2":0.15, "var3":0.7, "comp":"option1"},
        {"var1":0.7, "var2":0.15, "var3":0.15, "comp":"option1"},
        {"var1":0.6, "var2":0.2, "var3":0.2, "comp":"option2"},
        {"var1":0.2, "var2":0.6, "var3":0.2, "comp":"option2"},
        {"var1":0.2, "var2":0.2, "var3":0.6, "comp":"option2"},
        {"var1":0.6, "var2":0.2, "var3":0.2, "comp":"option2"}
               ]
    
    table=pd.DataFrame.from_dict(dummy_data)
    
    import plotly.graph_objects as go
    
    fig = go.Figure()
    
    table1 = table[table['comp'] == 'option1']
    fig.add_trace(go.Scatterternary(
        text=table1['comp'],
        a=table1['var1'],
        b=table1['var2'],
        c=table1['var3'],
        mode='lines',
        line_color='red',
        name='option1'
    
    ))
    
    table2 = table[table['comp'] == 'option2']
    fig.add_trace(go.Scatterternary(
        text=table2['comp'],
        a=table2['var1'],
        b=table2['var2'],
        c=table2['var3'],
        mode='lines',
        line_color='black',
        name='option2'
    ))
    
    
    fig.update_layout({
        'title': 'Ternary Line Plot',
        'ternary':
            {
            'sum':1,
            'aaxis':{'title': 'A', 'min': 0.01, 'linewidth':2, 'ticks':'outside' },
            'baxis':{'title': 'B', 'min': 0.01, 'linewidth':2, 'ticks':'outside' },
            'caxis':{'title': 'C', 'min': 0.01, 'linewidth':2, 'ticks':'outside' }
        },
        'showlegend': False
    })
    
    fig.update_layout(showlegend=True)
    fig.show()
    

    enter image description here