string variable as latex in pyplot

感情迁移 提交于 2021-01-02 06:44:26

问题


It is possible to have Latex formatting in pyplot diagrams, i.e. for title, labels etc.

#some dummy code
plt.plot(x,y,label = r"$a < \gamma$")

It is generated by adding an r before the actual latex string. Now, pyplot accepts variables as inputs for strings, i.e.

#some dummy code
foo = "some fancy label"
plt.plot(x,y, label = foo)

I would like to combine the two worlds, however the only answer I found on SO is for Julia.

How can I make this work?


回答1:


The example would look like:

foo = r"some fancy label and $a < \gamma$"
plt.plot(x,y, label = foo)

The point of adding an r is that it makes the string a raw string (literal). This is necessary because \ is no valid string literal. However, \ can be escaped by another \, such that the following is valid as well

foo = "some fancy label and $a < \\gamma$"
plt.plot(x,y, label = foo)

Note that there is no r in front of the string.

Also note that the dollar signs $ are not actually invoking latex but what is called MathText. In order to get true latex rendering you would need to have a working latex installation and invoke the usetex=True parameter; details here.



来源:https://stackoverflow.com/questions/44333065/string-variable-as-latex-in-pyplot

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