5

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!

SKchem
  • 51
  • 1
  • 2

1 Answers1

4

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

fernandezr
  • 660
  • 6
  • 19
  • 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? – SKchem Jun 16 '13 at 23:06
  • 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? – SKchem Jun 16 '13 at 23:19
  • 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) – fernandezr Jun 16 '13 at 23:26
  • 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? – SKchem Jun 16 '13 at 23:30
  • Other solution is using that (i just discovered): u"\u2082". This returns a subscript 2 – fernandezr Jun 16 '13 at 23:33
  • yes, I tried this one as well. Still shows the box. Seems that I need to change the font. from matplotlib import rc rc('font', **{'family':'sans-serif', 'sans-serif' ['Helvetica']}) error: font-family not found. Changing Helvetica to Arial works without error, but still writes the box instead of subscripted 2 – SKchem Jun 16 '13 at 23:42
  • Try other font with more unicode char support, like cambria or calibri [more](http://www.fileformat.info/info/unicode/char/2082/fontsupport.htm) – fernandezr Jun 16 '13 at 23:47