如何生成指数缩放轴?

时间:2011-02-04 15:09:14

标签: python matplotlib

请考虑以下代码:

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轴,但我无法想象如何做到这一点。这样做的原因是我显示的函数在开始时变化很小,但在有效间隔结束时开始更多地波动,所以我希望在结束时有更高的水平分辨率。如果有人可以为我的方法提出替代解决方案,请随意这样做!

2 个答案:

答案 0 :(得分:7)

这是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_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()

答案 1 :(得分: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