Plotting a non-continuous history graph: do not plot when condition

I am trying to plot a water temperature graph only when my heating is on. Not knowing my way very well, I asked ChatGPT for help and now have:

{% if is_state('switch.shelly1_b9cddb', 'on') %}
  {{ states('sensor.shellyplus1_441793cd2ba8_temperature') }}
{% else %}
  null
{% endif %}

Two problems:

  • the “null” value is seen as a string and generates errors;
  • it doesn’t do what I want:
    image

“Heating out temperature” (purple) is the source sensor and “Heating out cond” (orange) is the one from the above template sensor. Ideally, I would like those horizontal and vertical lines not to be plotted.

Is that possible?

Please don’t use Chat GPT, it frequently outputs nonsense.

You want something like this:

template:
  - sensor:
      - name: Water Temperature
        device_class: temperature
        state_class: measurement
        unit_of_measurement: "°C"
        state: "{{ states('sensor.shellyplus1_441793cd2ba8_temperature') }}"
        availability: "{{ is_state('switch.shelly1_b9cddb', 'on') }}"

This will set the template sensor state to unavailable if your switch is off, producing a gap in your graph.

EDIT: re-reading your post I think I got the wrong sensor, but you should get the idea. Use an availability template.

Thank you for your proposed solution. It looks good.

I had used a template helper to implement my version. It seems that the availability parameter is not available in the UI. I need to move (delete and create) it to configuration.yaml, right?

I did so and it plots as expected. Thanks!

My final result is as follows, just in case I am doing something suboptimal.

template:
  - sensor:
      - name: Heating in cond
        unique_id: sensor.heating_in_cond
        device_class: temperature
        state_class: measurement
        unit_of_measurement: "°C"
        state: "{{ states('sensor.shellyplus1_441793cd2ba8_temperature') }}"
        availability: "{{ is_state('switch.shelly1_b9cddb', 'on') }}"
      - name: "Filtered heating in cond"
        unique_id: sensor.filtered_heating_in_cond
        unit_of_measurement: "°C"
        device_class: temperature
        state_class: measurement ### only include this line if you want long term statistics. 
        state: "{{ states('sensor.heating_in_cond') if states('sensor.heating_in_cond')|is_number else null }}"        
        # ...repeat for "out" sensor...
sensor:
  - platform: statistics
    name: "heating in cond mean"
    entity_id: sensor.filtered_heating_in_cond
    state_characteristic: mean
    max_age:
      hours: 12

I took inspiration from your answer in the following post for the statistics part: How can avoid "unavailable" or "unknown" state in statistics template?. The aim being to take the average of the plotted values.