convert normal string to latex string to use in matplotlib

后端 未结 2 1759
温柔的废话
温柔的废话 2021-01-27 11:30

So I know that if I want to use a LaTeX string in my plots I should instead of for example \"sin(x)\", I should use r\"\\sin(x)\".

But if I hav

相关标签:
2条回答
  • 2021-01-27 11:59

    Use a = r"$\sin (x)$" Or alternatively convert variable a to b, like so:

    import matplotlib.pyplot as plt
    ax = plt.gca() 
    x = [1,2,3,4,5,6]  
    y = [324,456,6,78,2,54]  # cramming numbers on my keyboard
    a = "\sin(x)"
    b = r"$"+a+"$"
    ax.plot(x, y, label=b)
    
    ax.legend()
    plt.show()
    
    0 讨论(0)
  • 2021-01-27 12:06

    Mind that to have MathText activated the string must be in between Dollar signs ($).

    In case your latex contains backslashes you need to either use a raw string from the beginning

    a = r"$\tan(\nu\cdot x)$"
    

    or escape the backslashes

    a = "$\\tan(\\nu\\cdot x)$"
    

    If you try something like in the other answer, you'd get unexpected results

    a = "\tan(\nu\cdot x)"
    b = r"$"+a+"$"
    ax.plot(x, y, label=b)
    

    results in

    0 讨论(0)
提交回复
热议问题