Python function equivalent to R `pretty ()`?

I am replicating some R code in Python.

I rolled over on the R pretty().

All I need is pretty(x)where xis a numeric number.

Roughly speaking, the function "calculates beautiful breakpoints" as a sequence of several "round" values. I'm not sure there is a Python equivalent, and I'm not very lucky with Google.

Edit: more precisely, this description is in the help section for pretty:

Description. Compute a sequence of approximately n + 1 evenly distributed “round” values ​​that span a range of values ​​in x. Values ​​are selected so that they are 1, 2, or 5 times greater than 10.

I looked at R pretty.default()to find out exactly what R does with the function, but ultimately uses it .Internal(), which usually leads to the dark magic of R. I thought I would ask before diving.

Does anyone know if Python has something equivalent to R pretty()?

+6
source share
3 answers

I thought the psuedocode published by Lewis Fogden looked familiar, and we really once coded this pseudo-code in C ++ for the build routine (to determine axis symmetry). I quickly translated it into Python, not sure if this is like pretty()in R, but I hope this helps or is useful to anyone.

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)

This creates, for example:

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 1,5 2,5 2,5].

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

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

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

+6

, 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

What about numpy.arange?

import numpy as np

print np.arange(0,16,3)

$ [0 3 6 9 12 15]

0
source

Source: https://habr.com/ru/post/1016119/


All Articles