python matplotlib axis label subscript based on loop counter

别等时光非礼了梦想. 提交于 2019-12-12 17:16:32

问题


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.


回答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$'


来源:https://stackoverflow.com/questions/14712292/python-matplotlib-axis-label-subscript-based-on-loop-counter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!