How to produce an exponentially scaled axis?

后端 未结 2 987
轮回少年
轮回少年 2021-01-18 05:34

Consider the following code:

from numpy import log2
import matplotlib.pyplot as plt

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


        
2条回答
  •  失恋的感觉
    2021-01-18 06:36

    Here is how it is done. A good example to follow. You just subclass the ScaleBase class.

    Here's your transform. It's not too complicated when you whittle out all the custom formatters and stuff. Just a little verbose.

    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_non_affine(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_non_affine(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()
    

提交回复
热议问题