目前,如果我将matplotlib y轴tickleables设置为科学模式,它会在表单的y轴顶部给出一个指数1e-5
我想把它调整成r'$\mathregular{10^{-5}}$'
这样它就能很好地打印出来。
下面是我的示例代码:
# Create a figure and axis
fig, ax = plt.subplots()
# Plot 100 random points
# the y values of which are very small
ax.scatter(np.random.rand(100), np.random.rand(100)/100000.0)
# Set the y limits appropriately
ax.set_ylim(0, 1/100000.0)
# Change the y ticklabel format to scientific format
ax.ticklabel_format(axis='y', style='sci', scilimits=(-2, 2))
# Get the offset value
offset = ax.yaxis.get_offset_text()
# Print it out
print '1st offset printout: {}'.format(offset)
# Run plt.tight_layout()
plt.tight_layout()
# Print out offset again - you can see the value now!
print '2nd offset printout: {}'.format(offset)
# Change it to latex format
offset.set_text(r'$\mathregular{10^{-5}}$')
# Print it out
print '3rd offset printout: {}'.format(offset)
# Add some text to the middle of the figure just to
# check that it isn't the latex format that's the problem
ax.text(0.5, 0.5/100000.0, r'$\mathregular{10^{-2}}$')
# And show the figure
plt.show()
我的输出如下:
1st offset printout: Text(0,0.5,u'')
2nd offset printout: Text(0,636.933,u'1e\u22125')
3rd offset printout: Text(0,636.933,u'$\\mathregular{10^{-5}}$')
您可以找到代码并输出图here。
有两个奇怪的地方:一个是我不能覆盖y轴顶部的1e-5(这是目标),另一个是我必须运行plt.tight_layout()
才能看到unicode值作为偏移量。
有人能告诉我哪里出错了吗?
谢谢你
编辑:最初的问题没有说明我想自动检测当前由ticklabel_format
计算的指数。因此,与其将设置字符串传递给偏移文本,不如自动检测该值并相应地调整乳胶字符串。
基于@edsmith的答案,我想做的一个可能的工作是获取偏移文本,将其转换为乳胶字符串,关闭偏移并在轴的顶部添加该字符串。
注意,您应该可以通过调用
pos = ax_axis.get_offset_text().get_position()
来使用偏移文本的位置,但是这些值不是以轴为单位(它们可能是像素单位-谢谢@EdSmith-因此不是很有用)。因此,我只是根据我们所看到的轴来设置x_pos
和y_pos
值。我还编写了一个小函数来自动检测适当的x和y限制(尽管我知道matplotlib有很多奇特的方法可以做到这一点)。
因此,要根据问题更新我的示例(稍微更改一下,使两个轴都需要指数):
一个带有ipython笔记本的显示代码输出的要点是可用的here。
我希望这能有帮助!
您得到
offset
并设置文本值,但似乎没有办法将其实际应用于轴。。。即使调用ax.yaxis.offsetText.set_text(offset)
也不会更新显示的偏移量。解决方法是删除偏移文本并替换为轴标签上的括号或者替换为手动文本框,作为一个最小的例子
我知道这是不理想的,但可能是偏移文本不能手动更改或只能与数值一致。。。
似乎
plt.ticklabel_format
无法正常工作。但是,如果您自己定义ScalarFormatter并将科学符号的限制设置为formatter,则可以自动以mathtext格式获得偏移量,如下所示:相关问题 更多 >
编程相关推荐