From 443c3c2a5671e17018654f9fa7671fe7959b444c Mon Sep 17 00:00:00 2001 From: unhold Date: Wed, 12 Apr 2023 23:18:09 +0200 Subject: [PATCH] Fix graph limits for negative values and other corner cases (#4253) Fix lower graph limit for negative values by rounding down instead of truncating. Consistently handle the corner cases: empty trace, min=max (e.g. single value) by drawing the grid lines for a single grid division. --- esphome/components/graph/graph.cpp | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/esphome/components/graph/graph.cpp b/esphome/components/graph/graph.cpp index daff89e0a6..c229f17dd8 100644 --- a/esphome/components/graph/graph.cpp +++ b/esphome/components/graph/graph.cpp @@ -122,11 +122,18 @@ void Graph::draw(DisplayBuffer *buff, uint16_t x_offset, uint16_t y_offset, Colo } // Adjust limits to nice y_per_div boundaries - int yn = int(ymin / y_per_div); - int ym = int(ymax / y_per_div) + int(1 * (fmodf(ymax, y_per_div) != 0)); - ymin = yn * y_per_div; - ymax = ym * y_per_div; - yrange = ymax - ymin; + int yn = 0; + int ym = 1; + if (!std::isnan(ymin) && !std::isnan(ymax)) { + yn = (int) floorf(ymin / y_per_div); + ym = (int) ceilf(ymax / y_per_div); + if (yn == ym) { + ym++; + } + ymin = yn * y_per_div; + ymax = ym * y_per_div; + yrange = ymax - ymin; + } /// Draw grid if (!std::isnan(this->gridspacing_y_)) {