bre*_*ews 7 python numpy r scipy pandas
我在Python中复制一些R代码.
我绊倒了R's pretty().
所有我需要的是pretty(x),其中x一些数字.
粗略地说,函数"计算漂亮的断点"作为几个"圆"值的序列.我不确定是否有Python等价物,而且我对Google没有太多运气.
编辑:更具体地说,这是他帮助页面中的描述条目pretty:
描述:计算一个约为n + 1个等间距"圆"值的序列,它覆盖x中值的范围.选择这些值使得它们是10的幂的1,2或5倍.
我查看R是pretty.default()为了看看R究竟在做什么,但它最终会使用.Internal()- 这通常会导致黑暗R魔法.我以为在潜入之前我会问一下.
有谁知道Python是否有与R相当的东西pretty()?
我认为Lewis Fogden发布的伪代码看起来很熟悉,我们确实曾经用C++编写了伪代码来绘制例程(确定漂亮的轴标签).我很快将它翻译成Python,不确定它是否与pretty()R 类似,但我希望它对任何人都有帮助或有用.
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)
Run Code Online (Sandbox Code Playgroud)
这产生了例如:
pretty(0.5, 2.56, 10)
pretty(0.5, 25.6, 10)
pretty(0.5, 256, 10 )
pretty(0.5, 2560, 10)
Run Code Online (Sandbox Code Playgroud)
[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.]
它不像R那样优雅,但你仍然可以使用 numpy:
import numpy as np
np.linspace(a,b,n,dtype=int)
Run Code Online (Sandbox Code Playgroud)
其中a是范围的开头,b是结尾,n是值的数量,而输出类型是int。
例如:
np.linspace(0,10,11,dtype=int)
Run Code Online (Sandbox Code Playgroud)
数组([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
当然如果你想让它更优雅你可以这样包装:
pretty = lambda x: np.linspace(0,x,11,dtype=int)
pretty(10)
Run Code Online (Sandbox Code Playgroud)