2

Using Python and Pyplot, one of my plot labels was the following, which gave what I wanted.

plt.ylabel('$\mathrm{\dot{\nu}}$ ($\mathrm{10^{-16} s^{-2}}$)', fontsize=16)

Then instead of the label saying 10^-16, I wanted the label to be 10^-"power" where power is a variable that I have in my code.

I adjusted the code to:

plt.ylabel('$\mathrm{\dot{\nu}}$ ($\mathrm{10^{-{0}} s^{-2}}$)'.format(power), fontsize=16

But I get the following error:

KeyError: '\\dot{\\nu}'

The error seems like it doesn't know when I want to substitute "power" because of all the curly brackets, but I'm not sure how to fix it.

3 Answers 3

2

You need to escape all { chars—.format() treats them as special:

>>> '{0}'.format('foo')
'foo'
>>>
'{{{0}}}'.format('foo')  # => '{foo}'
'{foo}'

or

>>> power = 3
>>> '$\mathrm{{\dot{{\nu}}}}$ ($\mathrm{{10^{{-{0}}} s^{{-2}}}}$)'.format(power)
'$\\mathrm{\\dot{\nu}}$ ($\\mathrm{10^{-3} s^{-2}}$)'
Sign up to request clarification or add additional context in comments.

Comments

2

You can bypass all of this using the old format syntax:

>>> "%d, %d, %d" % (2, 2 ,4)
'2, 2, 4'
>>> 

In your case:

>>> '$\mathrm{{\dot{{\nu}}}}$ ($\mathrm{{10^{{-%d}} s^{{-2}}}}$)' % 2
'$\\mathrm{{\\dot{{\nu}}}}$ ($\\mathrm{{10^{{-2}} s^{{-2}}}}$)'
>>> 

Using strings:

>>> "%s world" % ('hello')
'hello world'
>>> 

Comments

1

You need to escape the { and } in your format string like so:

'$\mathrm{{\dot{{\nu}}}}$ ($\mathrm{{10^{{-{0}}} s^{{-2}}}}$)'

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.