How to create ternary contour plot in Python?

后端 未结 4 2071
余生分开走
余生分开走 2020-12-13 02:53

I have a data set as follows (in Python):

import numpy as np
A = np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0, 0.1, 0.2, 0.3, 0.4, 0.2, 0.2, 0.05         


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-13 03:20

    Just to add in another option (though probably too late to help the OP, but maybe someone else). You can pip install using pip install samternary. The github link is https://github.com/samueljmcameron/samternary.

    For the original post, you can follow the example examples/flatdata.py from the source code fairly closely, i.e.

    import matplotlib.pyplot as plt
    import numpy as np
    
    from samternary.ternary import Ternary
    
    # OP's data                                                             
    A = np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0,
                  0.1, 0.2, 0.3, 0.4, 0.2, 0.2, 0.05, 0.1])
    B = np.array([0.9, 0.7, 0.5, 0.3, 0.1, 0.2, 0.1, 0.15, 0, 0.1,
                  0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
    C = np.array([0, 0.1, 0.2, 0.3, 0.4, 0.2, 0.2, 0.05, 0.1, 0.9,
                  0.7, 0.5, 0.3, 0.1, 0.2, 0.1, 0.15, 0])
    D = np.array([1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1, 0,
                  1, 2])
    # note that the array C above is not necessary since A+B+C=1            
    
    
    # plot the data in two ways, in cartesian coordinates (ax_norm)         
    # and in ternary-plot coordinates (ax_trans)                            
    
    # create the figure and the two sets of axes                            
    fig, (ax_norm,ax_trans) = plt.subplots(1,2,
                                           figsize=[5,2.8])
    
    
    # plot data in normal way first using tricontourf                       
    ax_norm.tricontourf(A,B,D)
    ax_norm.set_xlabel(r'$\phi_1$')
    ax_norm.set_ylabel(r'$\phi_2$')
    
    # transform ax_trans to ternary-plot style, which includes              
    # building axes and labeling the axes                                   
    cob = Ternary(ax_trans, bottom_ax = 'bottom', left_ax = 'left',
                  right_ax = 'right',labelpad=20)
    
    # use change of bases method within Ternary() to                        
    points = cob.B1_to_B2(A,B)
    
    # affine transform x,y points to ternary-plot basis                     
    cs = ax_trans.tricontourf(points[0],points[1],D)
    
    
    ax_norm.set_title("Cartesian "
                      "(basis " + r"$\mathcal{B}_1$" + ")")
    ax_trans.set_title("flattened-grid "
                       "(basis " + r"$\mathcal{B}_2$" + ")")
    
    cbar = fig.colorbar(cs,ax=ax_trans,shrink=0.6)
    fig.subplots_adjust(bottom=0.2,hspace=0.01)
    plt.show()
    

    The result is (white spaces are due to the sparsity of the data from the OP):

    image of data in cartesian coordinates vs ternary plot

提交回复
热议问题