[英]On matplotlib logarithmic axes labels
尊敬的matplotlib社区,
关于对数轴标签,我有一个非常快速的问题,我敢肯定你们中的一员可以在戴上帽子时回答。
本质上我在matplotlib中有一个对数轴,标签为10 ^ -2、10 ^ -1、10 ^ 0、10 ^ 1、10 ^ 2等
但是,我想要0.01、0.1、1、10、100。
谁能在这方面指导我。 我尝试了一些选择,例如:
ax.set_xticks([0.01,0.1,1,10,100])
ax.set_xlabels([0.01,0.1,1,10,100])
任何专业提示将不胜感激!
首先,应代替set_xlabels
调用set_xticklabels
作为实际的刻度标签。 也就是说,至少在我当前的环境(python 2.7,matplotlib 1.4.3,OS X 10.10)中,这并不总是足够的。 在REPL(例如ipython)中逐条指令进行指令时,有时需要在调用set_xticklabels
之后更新轴。 一个快速的技巧是简单地调用grid(True)
或grid(False)
。 例如:
x = np.logspace(-2,2, 1000)
y = np.sin(x)
l = [0.01,0.1,1,10,100]
plt.semilogx(x,y)
plt.gca().set_xticks(l)
plt.gca().set_xticklabels(l)
plt.grid(True)
经验性注释:使用ipython的%paste
魔术贴粘贴要点时,似乎不需要使用grid(False)
技巧(有人知道为什么吗?)
一种不错的方法是使用matplotlib.ticker模块的FuncFormatter类。 结合您自己制作的自定义函数定义,这可以帮助您按所需的精确方式自定义刻度线。 此特定代码段与matplotlib使用的对数标度很好地配合。
import numpy as np
import matplotlib.pylab as plt
x = np.linspace(-10,10)
y = np.exp(x)
plt.close('all')
fig,ax = plt.subplots(1,1)
ax.plot(x,y,'bo')
ax.set_yscale('log')
#Placed the import/function definitions here to emphasize
#the working lines of code for this particular task.
from matplotlib.ticker import FuncFormatter
def labeller(x, pos):
"""
x is the tick value, pos is the position. These args are needed by
FuncFormatter.
"""
if x < 1:
return '0.'+'0'*(abs(int(np.log10(x)))-1)+\
format(x/10**(np.floor(np.log10(x))),'.0f')
else:
return format(x,'.0f')
#FuncFormatter class instance defined from the function above
custom_formatter = FuncFormatter(labeller)
ax.yaxis.set_major_formatter(custom_formatter)
plt.show()
结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.