Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python function equivalent to R's `pretty()`?

I'm replicating some R code in Python.

I've tripped up on R's pretty().

All I need is pretty(x), where x is some numeric.

Roughly, the function "computes pretty breakpoints" as a sequence of several "round" values. I'm not sure there is a Python equivalent and I'm not having much luck with Google.

Edit: More specifically, this is the Description entry in he help page for pretty:

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.

I looked into R's pretty.default() to see what exactly R is doing with the function but it eventually uses .Internal() -- which usually leads to dark R magic. I thought I'd ask around before diving in.

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

like image 903
brews Avatar asked Mar 28 '17 17:03

brews


1 Answers

I thought that the psuedocode posted by Lewis Fogden looked familiar, and we indeed once coded that pseudocode in C++ for a plotting routine (to determine pretty axis labels). I quickly translated it to Python, not sure if this is similar to pretty() in R, but I hope it 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 produces 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.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.]

like image 167
Bart Avatar answered Oct 10 '22 05:10

Bart