加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python函数相当于R的`pretty()`?

发布时间:2020-12-16 22:58:13 所属栏目:Python 来源:网络整理
导读:我在 Python中复制一些R代码. 我惹恼了R的漂亮(). 我需要的只是漂亮(x),其中x是一些数字. 粗略地说,函数“计算漂亮的断点”作为几个“圆”值的序列.我不确定是否有Python等价物,而且我对Google没有太多运气. 编辑:更具体地说,这是漂亮的帮助页面中的描述条
我在 Python中复制一些R代码.

我惹恼了R的漂亮().

我需要的只是漂亮(x),其中x是一些数字.

粗略地说,函数“计算漂亮的断点”作为几个“圆”值的序列.我不确定是否有Python等价物,而且我对Google没有太多运气.

编辑:更具体地说,这是漂亮的帮助页面中的描述条目:

Description: Compute a sequence of about n+1 equally spaced ‘round’ values which cover the range of the values in x. The values are chosen so that they are 1,2 or 5 times a power of 10.

我查看了R的pretty.default(),看看R究竟在做什么,但最终使用的是.Internal() – 这通常会导致黑暗R魔法.我以为在潜入之前我会问一下.

有谁知道Python是否有与R’s pretty()相同的东西?

解决方法

我认为Lewis Fogden发布的伪代码看起来很熟悉,我们确实曾在C中用伪代码编写了一个绘图例程(用于确定漂亮的轴标签).我很快将它翻译成Python,不确定它是否与R中的pretty()类似,但我希望它对任何人都有帮助或有用.
import numpy as np

def nicenumber(x,round):
    exp = np.floor(np.log10(x))
    f   = x / 10**exp

    if round:
        if f < 1.5:
            nf = 1.
        elif f < 3.:
            nf = 2.
        elif f < 7.:
            nf = 5.
        else:
            nf = 10.
    else:
        if f <= 1.:
            nf = 1.
        elif f <= 2.:
            nf = 2.
        elif f <= 5.:
            nf = 5.
        else:
            nf = 10.

    return nf * 10.**exp

def pretty(low,high,n):
    range = nicenumber(high - low,False)
    d     = nicenumber(range / (n-1),True)
    miny  = np.floor(low  / d) * d
    maxy  = np.ceil (high / d) * d
    return np.arange(miny,maxy+0.5*d,d)

这产生了例如:

pretty(0.5,2.56,10)
pretty(0.5,25.6,256,10 )
pretty(0.5,2560,10)

[ 0.5 1. 1.5 2. 2.5 3. ]

[ 0. 5. 10. 15. 20. 25. 30.]

[ 0. 50. 100. 150. 200. 250. 300.]

[ 0. 500. 1000. 1500. 2000. 2500. 3000.]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读