2

I'm using python and matplotlib to generate graphical output. I am creating multiple plots within a loop and would like the loop counter to serve as an index on the y-axis label. How do I get the loop counter (a variable) to appear as a subscript?

Here's what I have:

axis_ylabel = plt.ylabel(u"\u03b1 [\u00b0]", rotation='horizontal', position=(0.0,0.9))

resulting in:

α [°]

(I'm using unicode instead of Tex because dvipng is not available on this system.)

I would like something like this:

for i in range(1,3):  
  axis_ylabel = plt.ylabel(u"\u03b1" + str(i) + u" [\u00b0]", rotation='horizontal', position=(0.0,0.9))

No surprise, this gives:

α1 [°]
α2 [°]

What I really want is the numbers to be subscripts. How do I combine the conversion to a string with a command to create a subscript? Including a '_' is not recognized in the unicode environment to generate a subscript. Additionally, I still need python/matplotlib to recognize that this subscript-command should affect the following variable.
Any thoughts?

Edit

I got this far:

axis_ylabel = plt.ylabel(u"\u03b1" + r"$_" + str(i) + r"$" + u" [\u00b0]", rotation='horizontal', position=(0.0,0.9))  

-- this results in a subscript character. However, it is NOT a conversion of the integer value but a different symbol.

Edit 2
I am using python 2.6.6 and matplotlib 0.99.1.1. Inserting any kind of string at <> in r"$<>$" will not result in the display of that string but an entirely different character. I have posted this issue as a new question.

Community
  • 1
  • 1
Schorsch
  • 7,761
  • 6
  • 39
  • 65

1 Answers1

1

Matplotlib ships its own mathematical expression engine, called mathtext.
From the documentation:

Note that you do not need to have TeX installed, since matplotlib ships its own TeX expression parser, layout engine and fonts.

So maybe try to use the following:

for i in range(1,3):
    plt.ylabel(
           r"$\alpha_{:d} [\degree]$".format(i),
           rotation='horizontal',
           position=(0.0,0.9))

You can also use Unicode in mathtext:

If a particular symbol does not have a name (as is true of many of the more obscure symbols in the STIX fonts), Unicode characters can also be used:

 ur'$\u23ce$'
tzelleke
  • 15,023
  • 5
  • 33
  • 49
  • 1
    @Schorsch I cannot comprehend -- the code above works fine for me and your error report has nothing to do with matplotlib. Please post your code. – tzelleke Feb 05 '13 at 19:51
  • @Schorsch actually you should not be required to use unicode when mathtext works for you -- `r'$\alpha_2 [\degree]$'` should work -- note that `\alpha` is only interpreted inside `$...$`. If the format-syntax doesn't work, try the old syntax: `r'$\alpha_%d [\degree]$' % i` – tzelleke Feb 05 '13 at 21:28