Skip to content

Commit

Permalink
fix(log): color_thresholds render incorectly with logaritmic on (#542)
Browse files Browse the repository at this point in the history
Fixes #531
  • Loading branch information
RomRider authored and jlsjonas committed Jan 22, 2022
1 parent 57219bd commit b704885
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 4 deletions.
4 changes: 4 additions & 0 deletions .devcontainer/configuration.yaml
Expand Up @@ -34,3 +34,7 @@ sensor:
name: random_big
minimum: 12309812
maximum: 22309812
- platform: random
name: random_0_1000
minimum: 0
maximum: 1000
23 changes: 23 additions & 0 deletions .devcontainer/ui-lovelace.yaml
Expand Up @@ -30,3 +30,26 @@ views:
aggregate_func: median
- entity: sensor.random0_100
name: Random AVG
- type: custom:mini-graph-card
hours_to_show: 1
points_per_hour: 120
lower_bound: 0
upper_bound: 1000
logarithmic: true
smoothing: false
height: 400
show:
points: true
entities:
- entity: sensor.random_0_1000
name: log(0 - 1000) Gradients
aggregate_func: last
color_thresholds:
- value: 0
color: "#00ff00"
- value: 10
color: "#ffff00"
- value: 100
color: "#ff9900"
- value: 500
color: "#ff0000"
18 changes: 15 additions & 3 deletions src/graph.js
Expand Up @@ -153,8 +153,10 @@ export default class Graph {
return path;
}

computeGradient(thresholds) {
const scale = this._max - this._min;
computeGradient(thresholds, logarithmic) {
const scale = logarithmic
? Math.log10(Math.max(1, this._max)) - Math.log10(Math.max(1, this._min))
: this._max - this._min;

return thresholds.map((stop, index, arr) => {
let color;
Expand All @@ -165,9 +167,19 @@ export default class Graph {
const factor = (arr[index - 1].value - this._min) / (arr[index - 1].value - stop.value);
color = interpolateColor(arr[index - 1].color, stop.color, factor);
}
let offset;
if (scale <= 0) {
offset = 0;
} else if (logarithmic) {
offset = (Math.log10(Math.max(1, this._max))
- Math.log10(Math.max(1, stop.value)))
* (100 / scale);
} else {
offset = (this._max - stop.value) * (100 / scale);
}
return {
color: color || stop.color,
offset: scale <= 0 ? 0 : (this._max - stop.value) * (100 / scale),
offset,
};
});
}
Expand Down
4 changes: 3 additions & 1 deletion src/main.js
Expand Up @@ -739,7 +739,9 @@ class MiniGraphCard extends LitElement {
this.points[i] = this.Graph[i].getPoints();
}
if (config.color_thresholds.length > 0 && !config.entities[i].color)
this.gradient[i] = this.Graph[i].computeGradient(config.color_thresholds);
this.gradient[i] = this.Graph[i].computeGradient(
config.color_thresholds, this.config.logarithmic,
);
}
});
this.line = [...this.line];
Expand Down

0 comments on commit b704885

Please sign in to comment.