Pregunta

I have an equation which I need to show on a plot. The formula for the equation is quite long so I want to split it to not go beyond 80 chars with a single line.

Here's the MWE:

import matplotlib.pyplot as plt

num = 25

text = (r"$RE_{%d}$ = $\frac{\left(\sum^{l_k}{q_m} -\sum^{n}{f_h}\right) - |B_t - f_h+f_g)|}{B}$") % num

fig = plt.figure()
ax = fig.add_subplot(111)

plt.scatter([0., 1.], [0., 1.])
plt.text(0.5, 0.5, text, transform=ax.transAxes)

plt.show()

If I write it like that the plot is created with no issues, but when I try to break the text line I get all kinds of errors.

How should I do this?

¿Fue útil?

Solución

One simple possibility is to just use concatenation:

text = (r"$RE_{%d}$ = $\frac{\left(\sum^{l_k}{q_m} -\sum^{n}{f_h}\right) " +
        r" - |B_t - f_h+f_g)|}{B}$") % num

You could also use triple-quoted multiline strings, but then you need to substitute the line breaks manually:

def lf2space(s):
  return " ".join(s.split("\n"))

text = lf2space(r"""
    $RE_{%d} = 
       \frac{\left(\sum^{l_k}{q_m} -\sum^{n}{f_h}\right) 
                - |B_t - f_h+f_g)|}
            {B}$
  """ % num)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top