I have a very basic question : how to do a line break with matplotlib in python with an \"annotate\" command. I tried \"\\\" and \"\\n\" but it does not work. And how to do
What exactly did you try?
Were you, by chance, using a raw string (e.g. r"whatever"
)?
'\n'
works perfectly, but if you're using a raw string to avoid latex sequences being interpreted as an escape, it will be interpreted by python as '\'
and 'n'
instead of a newline.
As an example:
import matplotlib.pyplot as plt
plt.annotate('Testing\nThis\nOut', xy=(0.5, 0.5))
plt.show()
On the other hand, if we use a raw string:
import matplotlib.pyplot as plt
plt.annotate(r'Testing\nThis\nOut', xy=(0.5, 0.5))
plt.show()
Quick solutions
plt.annotate("I am \n"+r"$\frac{1}{2}$"+"\n in latex math environment", xy=(0.5, 0.5))
However, if you needed both, consider the following example:
import matplotlib.pyplot as plt
a = 1.23
b = 4.56
annotation_string = r"Need 1$^\mathsf{st}$ value here = %.2f" % (a)
annotation_string += "\n"
annotation_string += r"Need 2$^\mathsf{nd}$ value here = %.2f" % (b)
plt.annotate(annotation_string, xy=(0.5, 0.5))
plt.show()
Which gives you:
The key is to assemble the string beforehand, using +=
. That way, you can have the raw-string commands (indicated by r
) and the line-break (\n
) in the same annotation.
You can use the triple quotes when you define the annotation string, as in string="""some text"""
, so that the actual line breaks you type in your string will be interpreted as line breaks in the output. Here is an example, which includes latex and the printing of some numerical parameters from other parts of your code
import matplotlib.pyplot as plt
I = 100
T = 20
annotation_string = r"""The function plotted is:
$f(x) \ = \ \frac{{I}}{{2}} \cos\left(2 \pi \ \frac{{x}}{{T}}\right)$
where:
$I = ${0}
$T = ${1}""".format(I, T)
plt.annotate(annotation_string, xy=(0.05, 0.60), xycoords='axes fraction',
backgroundcolor='w', fontsize=14)
plt.show()
I have added some "extras":
the r
soon before the opening triple quotes, to facilitate the LaTeX interpreter
the double curly brackets {{}}
, so that the .format()
command and the LaTeX don't mess with each other
xycoords='axes fraction'
option, so to specify the position of
the string with fractional values with respect of the width and
height of the plotbackgroundcolor='w'
option, that puts a white marquee around
the annotation (convenient in case of overlapping with your plot)The plot obtained is this: