使用matplotlib / python的平方根刻度

发布于 2021-01-29 15:05:42

我想使用Python绘制平方根比例的图:

平方根比例图

但是,我不知道该怎么做。Matplotlib允许进行对数刻度,但是在这种情况下,我需要像幂函数刻度之类的东西。

关注者
0
被浏览
119
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您可以创建自己的ScaleBase课程来做。我已根据您的目的从此处修改了示例(该示例制作了正方形比例,而不是平方根比例)。另外,请参阅此处的文档。

    请注意,要正确执行此操作,您可能还应该创建自己的自定义刻度定位器。我在这里还没有做到;我只是使用手动设置主要和次要刻度线ax.set_yticks()

    import matplotlib.scale as mscale
    import matplotlib.pyplot as plt
    import matplotlib.transforms as mtransforms
    import matplotlib.ticker as ticker
    import numpy as np
    
    class SquareRootScale(mscale.ScaleBase):
        """
        ScaleBase class for generating square root scale.
        """
    
        name = 'squareroot'
    
        def __init__(self, axis, **kwargs):
            # note in older versions of matplotlib (<3.1), this worked fine.
            # mscale.ScaleBase.__init__(self)
    
            # In newer versions (>=3.1), you also need to pass in `axis` as an arg
            mscale.ScaleBase.__init__(self, axis)
    
        def set_default_locators_and_formatters(self, axis):
            axis.set_major_locator(ticker.AutoLocator())
            axis.set_major_formatter(ticker.ScalarFormatter())
            axis.set_minor_locator(ticker.NullLocator())
            axis.set_minor_formatter(ticker.NullFormatter())
    
        def limit_range_for_scale(self, vmin, vmax, minpos):
            return  max(0., vmin), vmax
    
        class SquareRootTransform(mtransforms.Transform):
            input_dims = 1
            output_dims = 1
            is_separable = True
    
            def transform_non_affine(self, a): 
                return np.array(a)**0.5
    
            def inverted(self):
                return SquareRootScale.InvertedSquareRootTransform()
    
        class InvertedSquareRootTransform(mtransforms.Transform):
            input_dims = 1
            output_dims = 1
            is_separable = True
    
            def transform(self, a):
                return np.array(a)**2
    
            def inverted(self):
                return SquareRootScale.SquareRootTransform()
    
        def get_transform(self):
            return self.SquareRootTransform()
    
    mscale.register_scale(SquareRootScale)
    
    fig, ax = plt.subplots(1)
    
    ax.plot(np.arange(0, 9)**2, label='$y=x^2$')
    ax.legend()
    
    ax.set_yscale('squareroot')
    ax.set_yticks(np.arange(0,9,2)**2)
    ax.set_yticks(np.arange(0,8.5,0.5)**2, minor=True)
    
    plt.show()
    

    在此处输入图片说明



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看