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

时间:2017-03-28 17:00:23

标签: python r pandas numpy scipy

我正在用Python复制一些R代码。

我绊倒了R pretty()

我需要的只是pretty(x),其中x是一些数字。

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

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

  

描述:计算大约n + 1个等间距'圆'值的序列,它覆盖x中值的范围。选择这些值使它们是10的幂的1,2或5倍。

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

有没有人知道Python是否具有与R pretty()相当的东西?

3 个答案:

答案 0 :(得分:7)

我认为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, 10)
pretty(0.5, 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。]

答案 1 :(得分:2)

它不像 R 那样优雅,但你仍然可以使用numpy:

import numpy as np
np.linspace(a,b,n,dtype=int)

其中a是范围的开头,b是结束,n是值的数量,而输出类型是int

例如:

np.linspace(0,10,11,dtype=int)
  

数组([0,1,2,3,4,5,6,7,8,9,10])

当然,如果你想要它更优雅,你可以包装它:

pretty = lambda x: np.linspace(0,x,11,dtype=int)
pretty(10)

答案 2 :(得分:0)

numpy.arange怎么样?

import numpy as np

print np.arange(0,16,3)
  

$ [0 3 6 9 12 15]

相关问题