nlu*_*igi 8 python matplotlib python-2.7
我有一个log-log图,范围从10^-3到10^+3.我希望值在指数中?10^0有一个+符号,类似于值如何在指数中<10^0有-符号.在matplotlib中有一个简单的方法吗?
我调查了一下,FuncFormatter但实现这一目标似乎过于复杂,我也无法让它发挥作用.
你可以用一个做到这一点FuncFormatter从matplotlib.ticker模块.你需要一个关于tick的值是否大于或小于1的条件.因此,如果log10(tick value)是>0,则+在标签字符串中添加符号,否则,它将自动获得其减号.
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
# sample data
x = y = np.logspace(-3,3)
# create a figure
fig,ax = plt.subplots(1)
# plot sample data
ax.loglog(x,y)
# this is the function the FuncFormatter will use
def mylogfmt(x,pos):
logx = np.log10(x) # to get the exponent
if logx < 0:
# negative sign is added automatically
return u"$10^{{{:.0f}}}$".format(logx)
else:
# we need to explicitly add the positive sign
return u"$10^{{+{:.0f}}}$".format(logx)
# Define the formatter
formatter = ticker.FuncFormatter(mylogfmt)
# Set the major_formatter on x and/or y axes here
ax.xaxis.set_major_formatter(formatter)
ax.yaxis.set_major_formatter(formatter)
plt.show()
Run Code Online (Sandbox Code Playgroud)
格式字符串的一些解释:
"$10^{{+{:.0f}}}$".format(logx)
Run Code Online (Sandbox Code Playgroud)
双括号{{并}}传递给LaTeX,表示其中的所有内容都应该作为指数提出.我们需要双括号,因为在这种情况下,python使用单个大括号来包含格式字符串{:.0f}.有关格式规范的更多说明,请参阅此处的文档,但请参阅TL;对于您的案例,我们正在格式化一个精度为0位小数的浮点数(即基本上将其打印为整数); 在这种情况下,exponent是一个float,因为np.log10返回一个float.(或者可以将输出转换为np.log10int,然后将字符串格式化为int - 只是您喜欢的偏好问题).
| 归档时间: |
|
| 查看次数: |
515 次 |
| 最近记录: |