How to display LaTeX f-strings in matplotlib [duplicate]

冷暖自知 提交于 2021-01-27 04:24:19

问题


In Python 3.6, there is the new f-string to include variables in strings which is great, but how do you correctly apply these strings to get super or subscripts printed for matplotlib?

(to actually see the result with the subscript, you need to draw the variable foo on a matplotlib plot)

In other words how do I get this behaviour:

    var = 123
    foo = r'text$_{%s}$' % var
    text<sub>123</sub>

Using the new f-string syntax? So far, I have tried using a raw-string literal combined with an f-string, but this only seems to apply the subscript to the first character of the variable:

    var = 123
    foo = fr'text$_{var}$'
    text<sub>1</sub>23

Because the { has an ambiguous function as delimiting what r should consider subscript and what f delimits as a place for the variable.


回答1:


You need to escape the curly brackets by doubling them up, and then add in one more to use in the LaTeX formula. This gives:

foo = f'text$_{{{var}}}$'

Example:

plt.figure()
plt.plot([1,2,3], [3,4,5])
var = 123
plt.text(1, 4,f'text$_{{{var}}}$')

Output:

Incidentally, in this example, you don't actually need to use a raw-string literal.



来源:https://stackoverflow.com/questions/60150031/how-to-display-latex-f-strings-in-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!