6

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!

1 Answer 1

5

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 "".

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

7 Comments

thanks, I already tried this (in the meantime). It returns in a different style than lables etc... Is there really no simple way without changing the style?
label=u'H\2082O' returns something weird... Sorry, I have no idea how to use unicode here...in your code line, the "2" is somewhat smaller ans subscripted, how did you do this?
Simply copy the line. Anyway, I got this looking on charmap utility (I'm on linux, but under Windows should works too. It has a charmap)
yes, I copied. But it returns a box for the subscripted "2"... I added # -- coding: utf-8 -- but it remains the same. Something with the font?
Other solution is using that (i just discovered): u"\u2082". This returns a subscript 2
|

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.