Average value in statistics graph, history graph; template sensor and statistics graph

Hi, I want to create a statistics graph of an entity that is the average of two sensors (template). Code:

chart_type: line
period: 5minute
type: statistics-graph
title: Humidity
entities:
  - sensor.esphome_web_74c344_average_humidity
  - entity: sensor.esphome_web_74c344_average_humidity
    name: humidity
stat_types:
  - mean
days_to_show: 1

I receive the message: Statistics not found.
average_humidity was created in ESPHome:

  - platform: template
    id: "soil_average"    
    name: "Average_humidity"
    unit_of_measurement: "%"
    accuracy_decimals: 2
    lambda: |-
      return (id(soil1).state + id(soil2).state)/2;
    update_interval: 30s

I was able to create statistics graphs of both sensors separately.
I can create a history graph. Is there a way to add mean of value to the history graph?

Add a device_class to your ESPHome sensor config to record LTS.

I have a question, if I add this line of code and upload (install) the code to ESP again, won’t it delete my sensor history in Home Assistant?

No it won’t. That will only happen if you change the name/entity_id.

Something like that?

  - platform: template
    id: "soil_average"    
    name: "Average humidity"
    unit_of_measurement: "%"
    accuracy_decimals: 2
    device_class: humidity
    lambda: |-
      return (id(soil1).state + id(soil2).state)/2;
    update_interval: 30s

Probably not because it didn’t work :frowning:

Sorry, that should have been state_class, not device_class.

  - platform: template
    id: "soil_average"    
    name: "Average_humidity"
    unit_of_measurement: "%"
    state_class: measurement
    device_class: humidity
    accuracy_decimals: 2
    lambda: |-
      return (id(soil1).state + id(soil2).state)/2;
    update_interval: 30s

It will take a little while for the LTS to be generated.

1 Like

It’s working but it doesn’t show graph before adding state_class: measurement and I need a graph from a few days ago. Normally I would use history-graph but there is no mean/average option there. Any advice?

No, sorry. LTS are only collected from the moment you add the state class. They are not calculated retroactively.

I’m experiencing the same problem. Sensor values are recalculated by use of template and lambda similar to the above, except I use interval: 10s instead of update interval.
I’ve added state_ and device_class as described here.
My dashboard shows the correct values from the lambda calculations, however the statistic chart cards shows “loading statistics” forever. And clicking on the sensor value in the entities card shows a history graph, so data is available.
Anyone any idea? Versions:

  • Core2024.4.4
  • Supervisor2024.04.0
  • Operating System12.2
  • Frontend20240404.2
    I’ll submit .yaml data if there’s no immediate ideas popping up…