Reputation: 61
this is my first question and I am a noob at python. So probably more to follow...
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()
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.
I figured that I could use
from matplotlib import rc
rc['text', usetex=True]
but I don't want to use it (I know how to use LaTeX, but I don't want here).
Another option is:
label='H$_2$O'
but this changes the font (math).
There MUST be a way, how does subscripting in matplotlib-legends work?
Thanks a lot!
Upvotes: 6
Views: 4195
Reputation: 690
Try to change this line
plt.plot(x,y, label='H2O')
for this:
plt.plot(x,y, label='$H_2O$')
It shows with the font math.
Or also you can use the unicode character for that: ₂ (0xE2 / ₂)
plt.plot(x,y, label=u'H₂O')
or instead:
plt.plot(x,y, label=u"H\u2082O")
Please, note that unicode strings are noted as u"" instead than "".
Upvotes: 5