问题描述
我正在使用python和matplotlib生成图形输出.我正在循环中创建多个图,并希望循环计数器充当y轴标签上的索引.如何使循环计数器(变量)显示为下标?
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?
这就是我所拥有的:
axis_ylabel = plt.ylabel(u"\u03b1 [\u00b0]", rotation='horizontal', position=(0.0,0.9))
导致:
α[°]
(我使用的是unicode而不是Tex,因为dvipng在该系统上不可用.)
(I'm using unicode instead of Tex because dvipng is not available on this system.)
我想要这样的东西:
for i in range(1,3):
axis_ylabel = plt.ylabel(u"\u03b1" + str(i) + u" [\u00b0]", rotation='horizontal', position=(0.0,0.9))
毫不奇怪,这给出了:
α1[°]
α2[°]
α1 [°]
α2 [°]
我真正想要的是要成为下标的数字.如何使用命令将对字符串的转换结合在一起以创建下标?在unicode环境中无法识别包含"_"以生成下标.此外,我仍然需要python/matplotlib来识别此下标命令应影响以下变量.
有什么想法吗?
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?
修改
我已经走了这么远:
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.
编辑2
我正在使用python 2.6.6和matplotlib 0.99.1.1.在r"$<>$"
中的<>
插入任何类型的字符串将不会显示该字符串,而是一个完全不同的字符.我已将此问题发布为新问题.
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.
推荐答案
Matplotlib附带了自己的数学表达式引擎,称为mathtext
.
从文档:
Matplotlib ships its own mathematical expression engine, called mathtext
.
From the documentation:
所以也许尝试使用以下内容:
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))
您也可以在mathtext
中使用Unicode:
You can also use Unicode in mathtext
:
ur'$\u23ce$'
这篇关于基于循环计数器的python matplotlib轴标签下标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!