Python Matplotlib-在要显示的行中使用$sign时如何添加多行文本框?
我需要在图形的文本框中的两行中绘制r平方和幂律方程,但我不能使用Python Matplotlib-在要显示的行中使用$sign时如何添加多行文本框?,python,matplotlib,Python,Matplotlib,我需要在图形的文本框中的两行中绘制r平方和幂律方程,但我不能使用'$a=3$\n$b=2$,因为我的代码中已经有了$符号。因此,每当我尝试添加&\&时,它都不起作用 'y='+str(round(m,3))+'x$^{'+str(round(j,3))+'}$' r$^{2}$=0.95 如何在图形的方框中以两行显示这些内容 谢谢我不确定这里有什么问题。如果在中间添加两个STATION和 \n>代码,对我来说是有效的: import matplotlib.pyplot as plt m,j
'$a=3$\n$b=2$
,因为我的代码中已经有了$
符号。因此,每当我尝试添加&\&
时,它都不起作用
'y='+str(round(m,3))+'x$^{'+str(round(j,3))+'}$'
r$^{2}$=0.95
如何在图形的方框中以两行显示这些内容
谢谢我不确定这里有什么问题。如果在中间添加两个STATION和<代码> \n>代码,对我来说是有效的:
import matplotlib.pyplot as plt
m,j=5.3421,2.6432
fig,ax = plt.subplots()
t='y='+str(round(m,3))+'x$^{'+str(round(j,3))+'}$\n r$^{2}$=0.95'
ax.text(0.5,0.5,t)
plt.show()
或者,可以使用字符串格式执行此操作:
t='y={:0}x$^{{{:1}}}$ \n r$^{{2}}$=0.95'.format(m,j)
请注意,格式字符串使用单大括号
{:0}
,latex代码使用双大括号{{2}
(因此,如果OP需要,在某些latex代码{{code>{1}}}}中包含格式字符串,则使用三大括号:
代码如下:
#!/usr/bin/python
import matplotlib
import matplotlib.pyplot
matplotlib.rc('text', usetex=True) #use latex for text
# add amsmath to the preamble
matplotlib.rcParams['text.latex.preamble']=[r"\usepackage{amsmath}"]
# data:
m, j = 5.3421, 2.6432
# insert a multiline latex expression
matplotlib.pyplot.text(0.2,0.2,
r'\[' # every line is a separate raw string...
r'\begin{split}' # ...but they are all concatenated by the interpreter :-)
r' y &= ' + str(round(m,3)) + 'x^{' + str(round(j,3)) + r'}\\'
r' r^2 &= 0.95 '
r'\end{split}'
r'\]',
size=50) # make it big so we can see it
matplotlib.pyplot.savefig("test.png")