Matplotlib - 在我想要显示的行中使用 $ 符号时如何添加多行文本框?

问题描述 投票:0回答:3

我需要在图中的文本框中的两行中绘制 r 平方和幂律方程,但我无法使用

'$a=3$\n$b=2$
,因为我的代码中已经有
$
符号。因此,每当我尝试添加
'& \ &'
时,它都不起作用。

'y='+str(round(m,3))+'x$^{'+str(round(j,3))+'}$'

r$^{2}$=0.95

如何在图形的框中将它们显示为两行?

python matplotlib
3个回答
7
投票

如果OP想要这个:

这是代码:

#!/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")

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}
,以及
{{2}}
代码的双大括号
latex
(因此,当某些乳胶代码中有格式字符串时,请使用三大括号
{{{:1}}}


0
投票

这是一个老问题,但只是一个友好的提醒,如果

\n
碍眼的话,你可以使用三引号在 Python 中创建多行字符串。

fig, ax = plt.subplots()
text = """
blah{0}
blah{1}
""".format(16,7)

ax.text(0, 1, text, ha='left', va='top',)

© www.soinside.com 2019 - 2024. All rights reserved.