Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TeX rendering, curly braces, and string formatting syntax in matplotlib

I have the following lines to render TeX annotations in my matplotlib plot:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc

rc('text', usetex=True)
rc('font', family='serif')

voltage = 220

notes = r"\noindent $V_2 = {0:.5} V$".format(voltage)

plt.annotate(notes, xy=(5,5), xytext=(7,7))
plt.show()

It works perfectly, but my first nitpick is that V is a unit of measure, therefore it should be in text mode, instead of (italicized) math mode. I try the following string:

notes = r"\noindent $V_2 = {0:.5} \text{V}$".format(voltage)

That raises an error, because {curly braces} are the ownership of Python's string formatting syntax. In the above line, only {0:.5} is correct; {V} is treated as a stranger. For example:

s1 = "Hello"
s2 = "World!"
print "Some string {0} {1}".format(s1, s2)

should give Some string Hello World!.

How do I make sure that TeX's {curly braces} do not interfere with Python's {curly braces}?

like image 653
Kit Avatar asked May 20 '11 07:05

Kit


People also ask

How do you use curly braces to format a string in Python?

If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }} . So if you want to print "{42}", you'd use "{{{0}}}". format(42) !

What is the use of {} in Python?

In languages like C curly braces ( {} ) are used to create program blocks used in flow control. In Python, curly braces are used to define a data structure called a dictionary (a key/value mapping), while white space indentation is used to define program blocks.

How do you escape curly brackets in F strings?

Python f-string escaping characters To escape a curly bracket, we double the character. A single quote is escaped with a backslash character.


1 Answers

You have to double the braces to be treated literally:

r"\noindent $V_2 = {0:.5} \text{{V}}$".format(voltage)

BTW, you can also write

\text V

but the best is

\mathrm V

since a unit is not really a text symbol.

like image 163
Philipp Avatar answered Oct 01 '22 21:10

Philipp