Skip to content

Commit 55ccea0

Browse files
committed
Make the Y labels more equidistant in line graphs
1 parent 6c367d9 commit 55ccea0

1 file changed

Lines changed: 40 additions & 4 deletions

File tree

assets/js/web-components/prpl-chart-line.js

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -169,23 +169,59 @@ customElements.define(
169169
.join( ' ' ) }" /></g>`;
170170
};
171171

172+
/**
173+
* Get the number of steps for the Y axis.
174+
*
175+
* Choose between 3, 4, or 5 steps.
176+
* The result should be the number that when used as a divisor,
177+
* produces integer values for the Y labels - or at least as close as possible.
178+
*
179+
* @return {number} The number of steps.
180+
*/
181+
getYLabelsStepsDivider = () => {
182+
const maxValuePadded = this.getMaxValuePadded();
183+
184+
const steps3Remainder = maxValuePadded % 3;
185+
const steps4Remainder = maxValuePadded % 4;
186+
const steps5Remainder = maxValuePadded % 5;
187+
188+
if ( steps4Remainder === 0 ) {
189+
return 4;
190+
} else if ( steps3Remainder === 0 ) {
191+
return 3;
192+
} else if ( steps5Remainder === 0 ) {
193+
return 5;
194+
} else if (
195+
steps3Remainder < steps4Remainder &&
196+
steps3Remainder < steps5Remainder
197+
) {
198+
return 3;
199+
} else if (
200+
steps5Remainder < steps3Remainder &&
201+
steps5Remainder < steps4Remainder
202+
) {
203+
return 5;
204+
}
205+
return 4;
206+
};
207+
172208
/**
173209
* Get the Y labels.
174210
*
175211
* @return {number[]} The Y labels.
176212
*/
177213
getYLabels = () => {
178214
const maxValuePadded = this.getMaxValuePadded();
179-
// Take the maximum value and divide it by 4 to get the step.
180-
const yLabelsStep = maxValuePadded / 4;
215+
const yLabelsStepsDivider = this.getYLabelsStepsDivider();
216+
const yLabelsStep = maxValuePadded / yLabelsStepsDivider;
181217
const yLabels = [];
182218
if ( 100 === maxValuePadded || 15 > maxValuePadded ) {
183-
for ( let i = 0; i <= 4; i++ ) {
219+
for ( let i = 0; i <= yLabelsStepsDivider; i++ ) {
184220
yLabels.push( parseInt( yLabelsStep * i ) );
185221
}
186222
} else {
187223
// Round the values to the nearest 10.
188-
for ( let i = 0; i <= 4; i++ ) {
224+
for ( let i = 0; i <= yLabelsStepsDivider; i++ ) {
189225
yLabels.push(
190226
Math.min(
191227
maxValuePadded,

0 commit comments

Comments
 (0)