0

With matplotlib, it is possible to use latex to label axes and plots. i.e.

import matplotlib.pyplot as plt

data = pandas.DataFrame({'A': [1, 2, 3, 4, 5],
                         'B': [6, 7, 8, 9, 10],
                         'C': [11, 12, 13, 14,15]})
data['A/B'] = data['A']/data['B']
plt.plot(data['C'], data['A/B'])
new_name1 = 'new_name'
new_name2 = 'new_name'
plt.title(r'$\frac{A}{B}$')
plt.show()

enter image description here

I would like to combine latex with python's string .format method. (While not necessary in this abstracted example, it is in my own work).

import matplotlib.pyplot as plt

data = pandas.DataFrame({'A': [1, 2, 3, 4, 5],
                         'B': [6, 7, 8, 9, 10],
                         'C': [11, 12, 13, 14,15]})
data['A/B'] = data['A']/data['B']
plt.plot(data['C'], data['A/B'])
new_name1 = 'new_name1'
new_name2 = 'new_name2'
plt.title(r'$\frac{\{\}}{\{\}}$'.format(new_name1, new_name2))
plt.show()

gives me:

Traceback (most recent call last):
  File "/home/b3053674/Documents/LargeStudy/large_study/plot_locally.py", line 912, in <module>
    plt.title(r'$\frac{\{\}}{\{\}}$'.format(new_name1, new_name2))
KeyError: '\\{\\}'

and

import matplotlib.pyplot as plt

data = pandas.DataFrame({'A': [1, 2, 3, 4, 5],
                         'B': [6, 7, 8, 9, 10],
                         'C': [11, 12, 13, 14,15]})
data['A/B'] = data['A']/data['B']
plt.plot(data['C'], data['A/B'])
new_name1 = 'new_name'
new_name2 = 'new_name'
plt.title(r'$\frac{{}}{{}}$'.format(new_name1, new_name2))
plt.show()

gives me:

ValueError: 
\frac{}{}
     ^
Expected \frac{num}{den} (at char 5), (line:1, col:6)

Is it possible to use string formatting with latex in this way? If so, how do I do it?

2 Answers 2

3

You need three braces:

plt.title(r'$\\frac{{{}}}{{{}}}$'.format(new_name1, new_name2))

The inner pair {} will be formatted using the given variables, and the outer {{ and }} are escape sequences for single { and }.

Sign up to request clarification or add additional context in comments.

2 Comments

Aaah of course, switching to latex means we need to use latex escape characters. Perfect, thanks.
@CiaranWelsh Not really, {{ is a python string format escape sequence.
1

A simple way is to use printf-like formatting:

data = "\frac{%s}{%s}" % ("A", "B")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.