在matplotlib标签中下标文本 [英] Subscripting text in matplotlib labels

查看:2703
本文介绍了在matplotlib标签中下标文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的第一个问题,我是python的菜鸟.所以可能还有更多...

this is my first question and I am a noob at python. So probably more to follow...

我想用matplotlib创建一个图形.在标签中,我想添加一个化学式,该化学式涉及下标(我认为上标也一样).

I would like to create a figure with matplotlib. In the labels, I would like to include a chemical formula, which involves subscripts (I think the same would work for superscripts...).

无论如何,我不知道标签的外观.

Anyway, I have no idea, how the label would have to look like.

import numpy as nu
import pylab as plt

x = nu.array([1,2,3,4])
y = nu.array([1,2,3,4])

plt.plot(x,y, label='H2O')
plt.legend(loc=1)
plt.show()

好的,这给了我一张标有"H2O"的图.与化学式一样,如何在标签上标上"2"?

Ok, this gives me a plot with the label "H2O". How can I subscript the "2" in the label, as is common for chemical formulae?

我搜索了网络,但没有发现有用的东西.

I searched the web, but I didn't find anything useful yet.

我认为我可以使用

from matplotlib import rc
rc['text', usetex=True]

但是我不想使用它(我知道如何使用LaTeX,但是我不想在这里使用).

but I don't want to use it (I know how to use LaTeX, but I don't want here).

另一个选择是:

label='H$_2$O'

但这会更改字体(数学).

but this changes the font (math).

必须有一种方法,matplotlib-legends中的下标如何工作?

There MUST be a way, how does subscripting in matplotlib-legends work?

非常感谢!

推荐答案

尝试更改此行

plt.plot(x,y, label='H2O')

为此:

plt.plot(x,y, label='$H_2O$')

它显示为带有数学字体.

It shows with the font math.

或者您也可以使用unicode字符:²(0xE2/²)

Or also you can use the unicode character for that: ₂ (0xE2 / ₂)

plt.plot(x,y, label=u'H₂O')

或者相反:

plt.plot(x,y, label=u"H\u2082O")

请注意,unicode字符串记为u"而不是".

Please, note that unicode strings are noted as u"" instead than "".

这篇关于在matplotlib标签中下标文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆