Skip to content

Instantly share code, notes, and snippets.

@MrTarantula
Created October 28, 2020 22:13
Show Gist options
  • Save MrTarantula/c930a5c0db9bdde7f565cea919bc5323 to your computer and use it in GitHub Desktop.
Save MrTarantula/c930a5c0db9bdde7f565cea919bc5323 to your computer and use it in GitHub Desktop.
Sane Y-axis ticks
using System;
using System.Collections.Generic;
public static class Chart
{
public static List<double> GetChartTicks(double minValue, double maxValue)
{
double diff = maxValue - minValue;
double initialValue = minValue;
// Round to nearest for lower bound of chart:
if (diff <= 1.0)
{
initialValue = Math.Floor(minValue * 10) / 10; // 0.10
}
else if (diff <= 5.0)
{
initialValue = Math.Floor(minValue); // 1.0
}
else if (diff <= 10.0)
{
initialValue = Math.Floor(minValue / 2) * 2; // 2.0
}
else
{
initialValue = Math.Floor(minValue / 5) * 5; // 5.0
}
// Chart tick increments.
//KEEP THESE IN DESCENDING ORDER!!!!
List<double> increments = new List<double> {
500.0,
400.0,
300.0,
250.0,
200.0,
100.0,
80.0,
60.0,
50.0,
45.0,
40.0,
35.0,
30.0,
25.0,
20.0,
15.0,
10.0,
8.0,
5.0,
2.5,
2.0,
1.0,
0.75,
0.5,
0.3,
0.25,
0.2,
0.15,
0.1,
0.05,
0.01
};
int incIndex = 0;
List<double> ticks = new List<double>();
bool processed = false;
// Starting with the largest increment, try to get at least six ticks
// If we don't get at least six, move on to the next lowest increment
while (!processed)
{
for (var x = 0; x < 10; x++)
{
if (initialValue + (increments[incIndex] * x) < maxValue)
{
ticks.Add(initialValue + (increments[incIndex] * x));
}
}
if (ticks.Count >= 6)
{
processed = true;
}
else
{
incIndex++;
ticks = new List<double>();
}
}
return ticks;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment