简体   繁体   English

如何在图例标签中使用字符串格式语法

[英]how to use string formatting syntax in a plot label

Using Python and Pyplot, one of my plot labels was the following, which gave what I wanted. 使用Python和Pyplot,我的图标签之一是下面的标签,它们给出了我想要的。

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. 然后,我希望标签不是10 ^ -16,而是10 ^-“ power”,其中power是代码中的变量。

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. 由于所有花括号,该错误似乎不知道何时要替换“ power”,但我不确定如何解决。

You need to escape all { chars— .format() treats them as special: 您需要转义所有{ chars。.format .format()将它们视为特殊值:

>>> '{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}}$)'

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'
>>> 

您需要像这样在格式字符串中转义{}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM