Overview
I need to produce text on a matplotlib.pyplot plot using text that both has different colours within the same object and has a number format specifier (using {:3.2f}.format(x)
).
Similar posts
I have found excellent posts on how to have different colours within the same object here and here and they both suggest using TeX and textcolor{}
.
This works fine but I am unsure of how to combine that with {}.format()
.
The closest thing I've found where Tex formatting and string formatting were combined was here, but I can't seem to find a way to make that work.
Where I got to
Say I want to create a text instance showing formatted x,y values printed as a float with two decimal places (3.2f) and different colours (blue, red, respectively). Here is what I thought would work:
import matplotlib
matplotlib.use('ps')
from matplotlib import rc
rc('text',usetex=True)
rc('text.latex', preamble=r'\usepackage{color}')
import matplotlib.pyplot as plt
plt.figure()
x, y = 1, 2
plt.plot(x, y, 'x')
string = r"$\textcolor{blue}{{:3.2f}}$".format(x) + '\n' + \
r"$\textcolor{red}{{:3.2f}}$".format(y)
plt.text(x=1, y=2, s=string)
I run into a KeyError: 'blue'
message if I run this code.
I am sure I misunderstand how these strings are interpreted but unfortunately there isn't any good documentation on this stuff.
Is it possible to combine things like \textcolor{}
with {}.format()
in plt.text()
? Or otherwise is there another way of achieving what I am after?