pythonmatplotliblegend

Legend in a specific format


I am plotting a graph with a legend using the following command:

K = [1e3,1e4]
plt.plot(x[:len(y1)], y1, 'o', label=f'Simulation ($K_L$={K[i]:0e})')

which produces the following graph:

enter image description here

But I want the legend to be in a specific format as presented below:

KL = 103


Solution

  • What about this? (insipred by this answer).

    import matplotlib.pyplot as plt
    
    
    def sci_notation(number: float, n_decimals: int = 2) -> str:
        sci_notation = f"{number:e}"
        decimal_part, exponent = sci_notation.split("e")
        decimal_part = float(decimal_part)
        exponent = int(exponent)
    
        if decimal_part == 1.0:
            return f"$10^{exponent}$"
        else:
            return f"{decimal_part:.{n_decimals}f}x$10^{exponent}$"
    
    
    K = [1e3, 1.323423e4]
    plt.plot([], [], "o", label=f"Simulation ($K_L$={sci_notation(K[0])})")
    plt.plot([], [], "o", label=f"Simulation ($K_L$={sci_notation(K[1])})")
    plt.legend()
    plt.show()
    

    enter image description here