Matplotlib - 如何在使用 $ 符号的行中添加多个行文本框?
我需要在图形的文本框中分别显示r平方值和幂律方程,但我不能使用'$a=3$\n$b=2$
,因为我的代码中已经有$
符号了。所以每次我尝试添加'& \ &'
时,它都不管用。
'y='+str(round(m,3))+'x$^{'+str(round(j,3))+'}$'
r$^{2}$=0.95
我该如何在图形的框中把这些内容显示成两行呢?
谢谢
相关文章:
- 暂无相关问题
3 个回答
3
我不太确定这里的问题是什么。如果你把这两个字符串中间加上一个 \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}}
(如果你在某些 latex 代码里面有格式字符串,那就需要用到三个大括号 {{{:1}}}
)。
7
如果提问者想要这个:
下面是代码:
#!/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")