Matplotlib - 如何在使用 $ 符号的行中添加多个行文本框?

5 投票
3 回答
15795 浏览
提问于 2025-05-11 02:13

我需要在图形的文本框中分别显示r平方值和幂律方程,但我不能使用'$a=3$\n$b=2$,因为我的代码中已经有$符号了。所以每次我尝试添加'& \ &'时,它都不管用。

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

r$^{2}$=0.95

我该如何在图形的框中把这些内容显示成两行呢?

谢谢

相关文章:

  • 暂无相关问题
暂无标签

3 个回答

0

这是一个老问题,但我想提醒一下,如果你觉得 \n 看起来不太好,可以使用三重引号来创建多行字符串,这样会更整洁。

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

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

在这里输入图片描述

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")

撰写回答