无论我使用的是 matplotlib、Open-Flash-Charts 还是其他图表框架,我总是需要找到一种方法来设置 x/y 比例限制和间隔,因为内置函数不够智能(或者根本不智能... )
只需在 pylab (ipyhton -pylab) 中尝试一下即可理解我的意思:
In [1]: a, b, x = np.zeros(10), np.ones(10), np.arange(10)
In [2]: plot(x, a); plot(x, b)
您会看到空白的框架网格隐藏了其顶部和底部边框下方的 2 条水平线。
我想知道是否有一些算法(我可以移植到 python)来巧妙地设置顶部和底部 y 限制和步长,并计算每个显示 x 厚的值的数量。
例如,假设我有 475 个度量为 (datetime, temperature)
作为(x, y)
与
2011-01-15 10:45:00 < datetime < 2011-01-17 02:20:00
(每 5 分钟一个)和
26.5 < temperature < 28.3
我对这种特殊情况的建议是设置:
26.4 <= y_scale <= 28.4
with a thick every.2
并勾选 x_scale
每 12 项(每小时一次)。
但是,如果我在 20 天内使用 -21.5 < temperature < 38.7
只有 20 个度量怎么办? , 等等?有没有标准化的方法?
最佳答案
以下是我多年来一直使用的方法,它既简单又运行良好。请原谅我是 C 语言,但转换为 Python 应该不难。
以下函数是必需的,来自 Graphic Gems 第 1 卷。
double NiceNumber (const double Value, const int Round) {
int Exponent;
double Fraction;
double NiceFraction;
Exponent = (int) floor(log10(Value));
Fraction = Value/pow(10, (double)Exponent);
if (Round) {
if (Fraction < 1.5)
NiceFraction = 1.0;
else if (Fraction < 3.0)
NiceFraction = 2.0;
else if (Fraction < 7.0)
NiceFraction = 5.0;
else
NiceFraction = 10.0;
}
else {
if (Fraction <= 1.0)
NiceFraction = 1.0;
else if (Fraction <= 2.0)
NiceFraction = 2.0;
else if (Fraction <= 5.0)
NiceFraction = 5.0;
else
NiceFraction = 10.0;
}
return NiceFraction*pow(10, (double)Exponent);
}
像下面的示例一样使用它,根据您希望显示的主要刻度数选择一个“不错”的轴起点/终点。如果您不关心刻度,则可以将其设置为常量值(例如:10)。
//Input parameters
double AxisStart = 26.5;
double AxisEnd = 28.3;
double NumTicks = 10;
double AxisWidth;
double NewAxisStart;
double NewAxisEnd;
double NiceRange;
double NiceTick;
/* Check for special cases */
AxisWidth = AxisEnd - AxisStart;
if (AxisWidth == 0.0) return (0.0);
/* Compute the new nice range and ticks */
NiceRange = NiceNumber(AxisEnd - AxisStart, 0);
NiceTick = NiceNumber(NiceRange/(NumTicks - 1), 1);
/* Compute the new nice start and end values */
NewAxisStart = floor(AxisStart/NiceTick)*NiceTick;
NewAxisEnd = ceil(AxisEnd/NiceTick)*NiceTick;
AxisStart = NewAxisStart; //26.4
AxisEnd = NewAxisEnd; //28.4
关于python - 智能计算图表刻度位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4947682/