2011-02-04 81 views
5

考虑下面的代码:如何生成指数缩放轴?

from numpy import log2 
import matplotlib.pyplot as plt 

xdata = [log2(x)*(10/log2(10)) for x in range(1,11)] 
ydata = range(10) 
plt.plot(xdata, ydata) 
plt.show() 

这将产生以下情节:The plot I do not want我的问题是,我怎么能修改此,这样的情节,具有完全相同的数据作为输入,显示为一条直线?这基本上需要适当地缩放X轴,但我不知道如何做到这一点。之所以这样做,是我显示该变化很小,在开始,但开始波动更倾向于能有效间隔结束的函数,所以我想有接近尾声较高水平分辨率。如果任何人都可以为我的方法提出一个替代解决方案,请随时这样做!

回答

5

这里是how它完成。一个好的example要遵循。你只是继承了ScaleBase类。

这是你的变换。当你减少所有的自定义格式化和东西时,这并不是太复杂。只是有点冗长。

from numpy import log2 
import matplotlib.pyplot as plt 

from matplotlib import scale as mscale 
from matplotlib import transforms as mtransforms 

class CustomScale(mscale.ScaleBase): 
    name = 'custom' 

    def __init__(self, axis, **kwargs): 
     mscale.ScaleBase.__init__(self) 
     self.thresh = None #thresh 

    def get_transform(self): 
     return self.CustomTransform(self.thresh) 

    def set_default_locators_and_formatters(self, axis): 
     pass 

    class CustomTransform(mtransforms.Transform): 
     input_dims = 1 
     output_dims = 1 
     is_separable = True 

     def __init__(self, thresh): 
      mtransforms.Transform.__init__(self) 
      self.thresh = thresh 

     def transform(self, a): 
      return 10**(a/10) 

     def inverted(self): 
      return CustomScale.InvertedCustomTransform(self.thresh) 

    class InvertedCustomTransform(mtransforms.Transform): 
     input_dims = 1 
     output_dims = 1 
     is_separable = True 

     def __init__(self, thresh): 
      mtransforms.Transform.__init__(self) 
      self.thresh = thresh 

     def transform(self, a): 
      return log2(a)*(10/log2(10)) 

     def inverted(self): 
      return CustomScale.CustomTransform(self.thresh) 


mscale.register_scale(CustomScale) 

xdata = [log2(x)*(10/log2(10)) for x in range(1,11)] 
ydata = range(10) 
plt.plot(xdata, ydata) 

plt.gca().set_xscale('custom') 
plt.show() 
2

最简单的方法是使用semilogy

from numpy import log2 
import matplotlib.pyplot as plt 

xdata = log2(range(1,11)) * (10/log2(10)) 
ydata = range(10) 
plt.semilogy(xdata, ydata) 
plt.show() 

enter image description here

+0

这有一个问题,即它不会显示小于1的y值。此外,它还会破坏具有较高x值的较高水平分辨率的目的。 – 2011-02-04 15:21:36

+0

它肯定会显示低于1的值! (即0.001 - > 10^-3),但不会显示0或低于0的值。对于“高x值的更高水平分辨率”,我对你的意思有些困惑......你的意思是你的实际情节的分辨率(即行中的分段数量)或你的xticks的位置......或者,你可能只是有一个破损的轴... – 2011-02-04 15:42:11