相当于R的`pretty()`的Python函数? [英] Python function equivalent to R's `pretty()`?

查看:162
本文介绍了相当于R的`pretty()`的Python函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm replicating some R code in Python.

我绊倒了R的pretty().

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

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

大致来说,该函数将计算断点"作为一系列舍入"值的序列.我不确定是否有Python等效版本,并且我对Google的运气不佳.

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.

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

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

说明:计算约n + 1个等间隔的舍入"值的序列,该值覆盖x中的值范围.选择的值应为10的幂的1、2或5倍.

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失去魔力.我以为我会在潜水前先问一下.

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.

有人知道Python是否具有与R的pretty()等效的东西吗?

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

推荐答案

我认为Lewis Fogden发布的伪代码看起来很熟悉,我们确实曾经用C ++将该伪代码编码为绘图例程(以确定 pretty 轴标签).我很快将其翻译为Python,不确定是否与R中的pretty()相似,但我希望它对任何人都有用或有用.

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)

这将产生例如:

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 1. 1.5 2. 2.5 3. ]

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

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

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

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

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

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

这篇关于相当于R的`pretty()`的Python函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆