我正在编写一些代码来在我们的软件中显示条形图(或线条)。一切都很顺利。令我难过的是标记Y轴。
来电者可以告诉我他们想要Y标记的标签有多精细,但我似乎仍然坚持以“有吸引力”的方式标记它们。我无法形容“有吸引力”,也许你也不能,但是当我们看到它时我们就知道了,对吗?
所以如果数据点是:
15, 234, 140, 65, 90
用户要求Y轴上有10个标签,用纸和铅笔进行一点点标记:
0, 25, 50, 75, 100, 125, 150, 175, 200, 225, 250
那里有10个(不包括0),最后一个延伸超出最高值(234 <250),并且它是每个25的“好”增量。如果他们要求8个标签,增量30就会很好看:
0, 30, 60, 90, 120, 150, 180, 210, 240
九会很棘手。也许只是使用了8或10,并将其称为足够接近就可以了。当一些观点是否定的时候该怎么办?
我可以看到Excel很好地解决了这个问题。
有没有人知道解决这个问题的通用算法(甚至有些蛮力可以)?我不必快速做,但看起来应该很好。
答案 0 :(得分:90)
很久以前我写了一个图形模块,很好地介绍了这个。挖掘灰色质量得到以下内容:
让我们举个例子:
15, 234, 140, 65, 90 with 10 ticks
所以范围= 0,25,50,...,225,250
您可以通过以下步骤获得良好的滴答范围:
在这种情况下,21.9除以10 ^ 2得到0.219。这是&lt; = 0.25所以我们现在有0.25。乘以10 ^ 2得到25。
让我们看一下8个刻度的相同例子:
15, 234, 140, 65, 90 with 8 ticks
给出您要求的结果; - )。
------由KD添加------
这是在不使用查找表等的情况下实现此算法的代码......:
double range = ...;
int tickCount = ...;
double unroundedTickSize = range/(tickCount-1);
double x = Math.ceil(Math.log10(unroundedTickSize)-1);
double pow10x = Math.pow(10, x);
double roundedTickRange = Math.ceil(unroundedTickSize / pow10x) * pow10x;
return roundedTickRange;
一般来说,刻度数包括底部刻度,因此实际的y轴段比刻度数少一个。
答案 1 :(得分:19)
这是我正在使用的PHP示例。此函数返回一个漂亮的Y轴值数组,其中包含传入的最小和最大Y值。当然,此例程也可用于X轴值。
它允许您“建议”您可能需要多少个刻度,但例程将返回 什么看起来不错。我添加了一些示例数据并显示了这些结果。
#!/usr/bin/php -q
<?php
function makeYaxis($yMin, $yMax, $ticks = 10)
{
// This routine creates the Y axis values for a graph.
//
// Calculate Min amd Max graphical labels and graph
// increments. The number of ticks defaults to
// 10 which is the SUGGESTED value. Any tick value
// entered is used as a suggested value which is
// adjusted to be a 'pretty' value.
//
// Output will be an array of the Y axis values that
// encompass the Y values.
$result = array();
// If yMin and yMax are identical, then
// adjust the yMin and yMax values to actually
// make a graph. Also avoids division by zero errors.
if($yMin == $yMax)
{
$yMin = $yMin - 10; // some small value
$yMax = $yMax + 10; // some small value
}
// Determine Range
$range = $yMax - $yMin;
// Adjust ticks if needed
if($ticks < 2)
$ticks = 2;
else if($ticks > 2)
$ticks -= 2;
// Get raw step value
$tempStep = $range/$ticks;
// Calculate pretty step value
$mag = floor(log10($tempStep));
$magPow = pow(10,$mag);
$magMsd = (int)($tempStep/$magPow + 0.5);
$stepSize = $magMsd*$magPow;
// build Y label array.
// Lower and upper bounds calculations
$lb = $stepSize * floor($yMin/$stepSize);
$ub = $stepSize * ceil(($yMax/$stepSize));
// Build array
$val = $lb;
while(1)
{
$result[] = $val;
$val += $stepSize;
if($val > $ub)
break;
}
return $result;
}
// Create some sample data for demonstration purposes
$yMin = 60;
$yMax = 330;
$scale = makeYaxis($yMin, $yMax);
print_r($scale);
$scale = makeYaxis($yMin, $yMax,5);
print_r($scale);
$yMin = 60847326;
$yMax = 73425330;
$scale = makeYaxis($yMin, $yMax);
print_r($scale);
?>
样本数据的结果输出
# ./test1.php
Array
(
[0] => 60
[1] => 90
[2] => 120
[3] => 150
[4] => 180
[5] => 210
[6] => 240
[7] => 270
[8] => 300
[9] => 330
)
Array
(
[0] => 0
[1] => 90
[2] => 180
[3] => 270
[4] => 360
)
Array
(
[0] => 60000000
[1] => 62000000
[2] => 64000000
[3] => 66000000
[4] => 68000000
[5] => 70000000
[6] => 72000000
[7] => 74000000
)
答案 2 :(得分:8)
试试这段代码。我已经在一些图表场景中使用它并且效果很好。它也很快。
public static class AxisUtil
{
public static float CalculateStepSize(float range, float targetSteps)
{
// calculate an initial guess at step size
float tempStep = range/targetSteps;
// get the magnitude of the step size
float mag = (float)Math.Floor(Math.Log10(tempStep));
float magPow = (float)Math.Pow(10, mag);
// calculate most significant digit of the new step size
float magMsd = (int)(tempStep/magPow + 0.5);
// promote the MSD to either 1, 2, or 5
if (magMsd > 5.0)
magMsd = 10.0f;
else if (magMsd > 2.0)
magMsd = 5.0f;
else if (magMsd > 1.0)
magMsd = 2.0f;
return magMsd*magPow;
}
}
答案 3 :(得分:6)
听起来调用者没有告诉你它想要的范围。
所以你可以自由地改变终点,直到你的标签数量可以很好地整除它。
让我们定义“好”。如果标签关闭,我会称之为好的:
1. 2^n, for some integer n. eg. ..., .25, .5, 1, 2, 4, 8, 16, ...
2. 10^n, for some integer n. eg. ..., .01, .1, 1, 10, 100
3. n/5 == 0, for some positive integer n, eg, 5, 10, 15, 20, 25, ...
4. n/2 == 0, for some positive integer n, eg, 2, 4, 6, 8, 10, 12, 14, ...
查找数据系列的最大值和最小值。我们称之为:
min_point and max_point.
现在你需要做的就是找到3个值:
- start_label, where start_label < min_point and start_label is an integer
- end_label, where end_label > max_point and end_label is an integer
- label_offset, where label_offset is "nice"
符合等式:
(end_label - start_label)/label_offset == label_count
可能有很多解决方案,所以选择一个。大多数时候我打赌你可以设置
start_label to 0
所以只需尝试不同的整数
end_label
直到偏移量为“漂亮”
答案 4 :(得分:3)
我还在努力争取这个:)
原始的Gamecat答案似乎在大多数情况下都有效,但尝试插入说“3滴答”作为所需的滴答数(对于相同的数据值15,234,140,65,90)。 ..它似乎给出了一个73的刻度范围,除以10 ^ 2后得到0.73,它映射到0.75,这给出了一个“漂亮”的刻度范围75.
然后计算上限: 75 *圆(1 + 234/75)= 300
和下限: 75 *轮(15/75)= 0
但是很明显,如果你从0开始,然后以75的步长前进到300的上限,你最终会得到0,75,150,225,300 ....这无疑是有用的,但它是4个刻度(不包括0)而不是所需的3个刻度。
令人沮丧的是,它在100%的时间内都不起作用......当然,这可能是我的错误!
答案 5 :(得分:3)
Toon Krijthe的答案大部分时间都有效。但有时它会产生过多的滴答声。它也不会与负数一起工作。问题的总体方法还可以,但有一种更好的方法可以解决这个问题。您想要使用的算法将取决于您真正想要获得的内容。下面我将向您展示我在JS Ploting库中使用的代码。我已经对它进行了测试,它总能正常工作(希望如此;))。以下是主要步骤:
让我们开始。首先是基本计算
var range = Math.abs(xMax - xMin); //both can be negative
var rangeOrder = Math.floor(Math.log10(range)) - 1;
var power10 = Math.pow(10, rangeOrder);
var maxRound = (xMax > 0) ? Math.ceil(xMax / power10) : Math.floor(xMax / power10);
var minRound = (xMin < 0) ? Math.floor(xMin / power10) : Math.ceil(xMin / power10);
我将最小值和最大值舍入为100%,确保我的绘图将覆盖所有数据。对于范围的log10或者它是否是负的并且稍后减去1也是非常重要的。否则,您的算法不会对小于1的数字起作用。
var fullRange = Math.abs(maxRound - minRound);
var tickSize = Math.ceil(fullRange / (this.XTickCount - 1));
//You can set nice looking ticks if you want
//You can find exemplary method below
tickSize = this.NiceLookingTick(tickSize);
//Here you can write a method to determine if you need zero tick
//You can find exemplary method below
var isZeroNeeded = this.HasZeroTick(maxRound, minRound, tickSize);
我使用&#34;漂亮的滴答声&#34;避免像7,13,17等蜱。我在这里使用的方法非常简单。在需要时使用zeroTick也很不错。 Plot看起来更专业。您将在本答案的最后找到所有方法。
现在你必须计算上限和下限。零刻度非常容易,但在其他情况下需要更多的努力。为什么?因为我们想要将情节很好地集中在上下限内。看看我的代码。某些变量是在此范围之外定义的,其中一些变量是保存整个显示代码的对象的属性。
if (isZeroNeeded) {
var positiveTicksCount = 0;
var negativeTickCount = 0;
if (maxRound != 0) {
positiveTicksCount = Math.ceil(maxRound / tickSize);
XUpperBound = tickSize * positiveTicksCount * power10;
}
if (minRound != 0) {
negativeTickCount = Math.floor(minRound / tickSize);
XLowerBound = tickSize * negativeTickCount * power10;
}
XTickRange = tickSize * power10;
this.XTickCount = positiveTicksCount - negativeTickCount + 1;
}
else {
var delta = (tickSize * (this.XTickCount - 1) - fullRange) / 2.0;
if (delta % 1 == 0) {
XUpperBound = maxRound + delta;
XLowerBound = minRound - delta;
}
else {
XUpperBound = maxRound + Math.ceil(delta);
XLowerBound = minRound - Math.floor(delta);
}
XTickRange = tickSize * power10;
XUpperBound = XUpperBound * power10;
XLowerBound = XLowerBound * power10;
}
以下是我之前提到的方法,您可以自己编写,但也可以使用我的
this.NiceLookingTick = function (tickSize) {
var NiceArray = [1, 2, 2.5, 3, 4, 5, 10];
var tickOrder = Math.floor(Math.log10(tickSize));
var power10 = Math.pow(10, tickOrder);
tickSize = tickSize / power10;
var niceTick;
var minDistance = 10;
var index = 0;
for (var i = 0; i < NiceArray.length; i++) {
var dist = Math.abs(NiceArray[i] - tickSize);
if (dist < minDistance) {
minDistance = dist;
index = i;
}
}
return NiceArray[index] * power10;
}
this.HasZeroTick = function (maxRound, minRound, tickSize) {
if (maxRound * minRound < 0)
{
return true;
}
else if (Math.abs(maxRound) < tickSize || Math.round(minRound) < tickSize) {
return true;
}
else {
return false;
}
}
此处不再包含一件事。这是&#34;漂亮的边界&#34;。这些是下限,这些数字类似于&#34;漂亮的蜱和#34;中的数字。例如,最好让下限从5开始,刻度尺寸为5,而不是从具有相同刻度尺寸的6开始的绘图。但我解雇了,我把它留给你了。
希望它有所帮助。 干杯!
答案 6 :(得分:1)
//get proper scale for y
$maximoyi_temp= max($institucion); //get max value from data array
for ($i=10; $i< $maximoyi_temp; $i=($i*10)) {
if (($divisor = ($maximoyi_temp / $i)) < 2) break; //get which divisor will give a number between 1-2
}
$factor_d = $maximoyi_temp / $i;
$factor_d = ceil($factor_d); //round up number to 2
$maximoyi = $factor_d * $i; //get new max value for y
if ( ($maximoyi/ $maximoyi_temp) > 2) $maximoyi = $maximoyi /2; //check if max value is too big, then split by 2
答案 7 :(得分:0)
感谢您提出问题和答案,非常有帮助。 Gamecat,我想知道你是如何确定应该舍入到的范围。
滴答范围= 21.9。这应该是25.0
为了在算法上做到这一点,人们必须在上面的算法中添加逻辑,以便为更大的数字做好这个尺度? 例如,如果范围是3346,那么蜱范围将评估为334.6并且当350可能更好时,舍入到最接近的10将给出340。
您怎么看?
答案 8 :(得分:0)
根据@ Gamecat的算法,我制作了以下助手类
public struct Interval
{
public readonly double Min, Max, TickRange;
public static Interval Find(double min, double max, int tickCount, double padding = 0.05)
{
double range = max - min;
max += range*padding;
min -= range*padding;
var attempts = new List<Interval>();
for (int i = tickCount; i > tickCount / 2; --i)
attempts.Add(new Interval(min, max, i));
return attempts.MinBy(a => a.Max - a.Min);
}
private Interval(double min, double max, int tickCount)
{
var candidates = (min <= 0 && max >= 0 && tickCount <= 8) ? new[] {2, 2.5, 3, 4, 5, 7.5, 10} : new[] {2, 2.5, 5, 10};
double unroundedTickSize = (max - min) / (tickCount - 1);
double x = Math.Ceiling(Math.Log10(unroundedTickSize) - 1);
double pow10X = Math.Pow(10, x);
TickRange = RoundUp(unroundedTickSize/pow10X, candidates) * pow10X;
Min = TickRange * Math.Floor(min / TickRange);
Max = TickRange * Math.Ceiling(max / TickRange);
}
// 1 < scaled <= 10
private static double RoundUp(double scaled, IEnumerable<double> candidates)
{
return candidates.First(candidate => scaled <= candidate);
}
}
答案 9 :(得分:0)
上述算法没有考虑最小值和最大值之间的范围太小的情况。如果这些值远远高于零怎么办?然后,我们有可能以高于零的值开始y轴。另外,为了避免我们的线完全位于图形的上侧或下侧,我们必须给它一些空气来呼吸#34;。
为了涵盖我在(PHP上)编写的上述代码:
function calculateStartingPoint($min, $ticks, $times, $scale) {
$starting_point = $min - floor((($ticks - $times) * $scale)/2);
if ($starting_point < 0) {
$starting_point = 0;
} else {
$starting_point = floor($starting_point / $scale) * $scale;
$starting_point = ceil($starting_point / $scale) * $scale;
$starting_point = round($starting_point / $scale) * $scale;
}
return $starting_point;
}
function calculateYaxis($min, $max, $ticks = 7)
{
print "Min = " . $min . "\n";
print "Max = " . $max . "\n";
$range = $max - $min;
$step = floor($range/$ticks);
print "First step is " . $step . "\n";
$available_steps = array(5, 10, 20, 25, 30, 40, 50, 100, 150, 200, 300, 400, 500);
$distance = 1000;
$scale = 0;
foreach ($available_steps as $i) {
if (($i - $step < $distance) && ($i - $step > 0)) {
$distance = $i - $step;
$scale = $i;
}
}
print "Final scale step is " . $scale . "\n";
$times = floor($range/$scale);
print "range/scale = " . $times . "\n";
print "floor(times/2) = " . floor($times/2) . "\n";
$starting_point = calculateStartingPoint($min, $ticks, $times, $scale);
if ($starting_point + ($ticks * $scale) < $max) {
$ticks += 1;
}
print "starting_point = " . $starting_point . "\n";
// result calculation
$result = [];
for ($x = 0; $x <= $ticks; $x++) {
$result[] = $starting_point + ($x * $scale);
}
return $result;
}
答案 10 :(得分:0)
将此answer转换为 Swift 4
extension Int {
static func makeYaxis(yMin: Int, yMax: Int, ticks: Int = 10) -> [Int] {
var yMin = yMin
var yMax = yMax
var ticks = ticks
// This routine creates the Y axis values for a graph.
//
// Calculate Min amd Max graphical labels and graph
// increments. The number of ticks defaults to
// 10 which is the SUGGESTED value. Any tick value
// entered is used as a suggested value which is
// adjusted to be a 'pretty' value.
//
// Output will be an array of the Y axis values that
// encompass the Y values.
var result = [Int]()
// If yMin and yMax are identical, then
// adjust the yMin and yMax values to actually
// make a graph. Also avoids division by zero errors.
if yMin == yMax {
yMin -= ticks // some small value
yMax += ticks // some small value
}
// Determine Range
let range = yMax - yMin
// Adjust ticks if needed
if ticks < 2 { ticks = 2 }
else if ticks > 2 { ticks -= 2 }
// Get raw step value
let tempStep: CGFloat = CGFloat(range) / CGFloat(ticks)
// Calculate pretty step value
let mag = floor(log10(tempStep))
let magPow = pow(10,mag)
let magMsd = Int(tempStep / magPow + 0.5)
let stepSize = magMsd * Int(magPow)
// build Y label array.
// Lower and upper bounds calculations
let lb = stepSize * Int(yMin/stepSize)
let ub = stepSize * Int(ceil(CGFloat(yMax)/CGFloat(stepSize)))
// Build array
var val = lb
while true {
result.append(val)
val += stepSize
if val > ub { break }
}
return result
}
}
答案 11 :(得分:0)
对于在ES5 Javascript中需要此功能的任何人,都需要进行一些努力,但这是:
var min=52;
var max=173;
var actualHeight=500; // 500 pixels high graph
var tickCount =Math.round(actualHeight/100);
// we want lines about every 100 pixels.
if(tickCount <3) tickCount =3;
var range=Math.abs(max-min);
var unroundedTickSize = range/(tickCount-1);
var x = Math.ceil(Math.log10(unroundedTickSize)-1);
var pow10x = Math.pow(10, x);
var roundedTickRange = Math.ceil(unroundedTickSize / pow10x) * pow10x;
var min_rounded=roundedTickRange * Math.floor(min/roundedTickRange);
var max_rounded= roundedTickRange * Math.ceil(max/roundedTickRange);
var nr=tickCount;
var str="";
for(var x=min_rounded;x<=max_rounded;x+=roundedTickRange)
{
str+=x+", ";
}
console.log("nice Y axis "+str);
基于Toon Krijtje的出色回答。
答案 12 :(得分:0)
这是我发现的另一个Java example来的。
const niceScale = ( minPoint, maxPoint, maxTicks) => {
const niceNum = ( localRange, round) => {
var exponent,fraction,niceFraction;
exponent = Math.floor(Math.log10(localRange));
fraction = localRange / Math.pow(10, exponent);
if (round) {
if (fraction < 1.5) niceFraction = 1;
else if (fraction < 3) niceFraction = 2;
else if (fraction < 7) niceFraction = 5;
else niceFraction = 10;
} else {
if (fraction <= 1) niceFraction = 1;
else if (fraction <= 2) niceFraction = 2;
else if (fraction <= 5) niceFraction = 5;
else niceFraction = 10;
}
return niceFraction * Math.pow(10, exponent);
}
const result = [];
const range = niceNum(maxPoint - minPoint, false);
const stepSize = niceNum(range / (maxTicks - 1), true);
const lBound = Math.floor(minPoint / stepSize) * stepSize;
const uBound = Math.ceil(maxPoint / stepSize) * stepSize;
for(let i=lBound;i<=uBound;i+=stepSize) result.push(i);
return result;
};
console.log(niceScale(15,234,6));
// > [0, 100, 200, 300]
答案 13 :(得分:0)
accepted answer 的演示
function tickEvery(range, ticks) {
return Math.ceil((range / ticks) / Math.pow(10, Math.ceil(Math.log10(range / ticks) - 1))) * Math.pow(10, Math.ceil(Math.log10(range / ticks) - 1));
}
function update() {
const range = document.querySelector("#range").value;
const ticks = document.querySelector("#ticks").value;
const result = tickEvery(range, ticks);
document.querySelector("#result").textContent = `With range ${range} and ${ticks} ticks, tick every ${result} for a total of ${Math.ceil(range / result)} ticks at ${new Array(Math.ceil(range / result)).fill(0).map((v, n) => Math.round(n * result)).join(", ")}`;
}
update();
<input id="range" min="1" max="10000" oninput="update()" style="width:100%" type="range" value="5000" width="40" />
<br/>
<input id="ticks" min="1" max="20" oninput="update()" type="range" style="width:100%" value="10" />
<p id="result" style="font-family:sans-serif"></p>