Dynamically select the number of hours or sensors to show on a history graph or mini graph card

@AleXSR7001

You have not defined your variables correctly. Here’s the correct code:

type: vertical-stack
cards:
  - type: entities
    entities:
      - entity: input_select.days_back_card
        name: Days Back
      - entity: input_select.sensors_to_show
        name: Select Sensor
  - type: custom:config-template-card
    entities:
      - input_select.days_back_card
      - input_select.sensors_to_show
    variables:
      sensor: states['input_select.sensors_to_show'].state
      days: |
        -states['input_select.days_back_card'].state+'d'
    card:
      type: custom:apexcharts-card
      graph_span: 24h
      span:
        start: day
        offset: ${days}
      series:
        - entity: ${sensor}
          stroke_width: 2
          group_by:
            func: median
            duration: 5min

Ahhhh, now I see!
Thank you again!

I only just realized that “days_back” can be misunderstood. :smiley:
As is, it isn’t showing the number of days including today. So if you select 1, it should show today. If you select 2, it should be today and yesterday. Played around but did not manage to get it working. I would have thought that the offset would need to be 0 to display the current day. But maybe that is not as easy as in this case the graph_span would show time in the future with no data (which would be the correct way to display it, but maybe causes a code error?).
So I am guessing that the “offset” would need to be conditional?

I am not really sure, since I am not using it myself.
Have a look at the apex chart card documentation to find out more information regarding the offset option.

I looked at the start, end and offsetoptions before posting and I did not see anything useful. But I think that the approach might need to be changed. Rather than using just the offset, maybe one needs to adjust the graph_span also?

So I think it has to be

    card:
      type: custom:apexcharts-card
      graph_span: ${days}
      span:
        start: day
        offset: 1-${days}

But my offset syntax is wrong. Sorry, I am still not quite familiar with the templating syntax used by HA and find it quite counter-intuitive :frowning:

P.S.: I did test it, btw, and the approach works. Just the offset syntax needs fixing

If you want to display the current day, would’n it be simpler to add ‘0’ as an option in the input_select?
Then if you choose ‘0’ it would show today, ‘1’ yesterday and so on…
This way you don’t have to change the code.

No, not really, because I almost always want to see today versus a different day. So the present day always needs to be part of it.
If I add 0, then I only add today but never can I see today and x days back.

Solved it:

    variables:
      sensor: states['input_select.sensors_to_show'].state
      span: states['input_select.days_back_to_show'].state+'d'
      days: |
        -states['input_select.days_back_to_show'].state+'d'+'1d'
    card:
      type: custom:apexcharts-card
      graph_span: ${span}
      span:
        start: day
        offset: ${days}

Defined a separate variable for span and the simply added ‘1d’ to the days_to_show sensor

Try this

    variables:
      days: |
        (1-states['input_select.days_back_card'].state)+'d'
    card:
      type: custom:apexcharts-card
      graph_span: 24h
      span:
        start: day
        offset: ${'-'+days}

And similarly for the span option…

Now I just need to figure out the multiple choice thing. It seems that there is dropdown as input_select but I need to take a look at it

Ok this seems to work too!

I was wondering: is this not kind of the wrong way around?
Auto entities could create the list of available areas, eliminating the need to create an input_select for areas.

So would it not be possible to use auto entities to populate an areas dropdown which then serves as variable to the next card?

Hi there,
I’m using this code and all is working like a charm! Thanks a lot!
I’m trying to set a friendly name for the options of my input_select.
Now the dropdown list shows f.e. sensor_temperature_kitchen… i wolud display “Kitcken”…
How to solve?? Thanks a lot.

1 Like

Hey folks, I was able to setup a history-graph with configurable “hours to show” input.

I have a problem though, it does not update, no new data are shown in a graph until I somehow refresh the dashboard.

Normally deployed history graph refreshes properly.

Any ideas?

@ellox
In the “entities” part of the config-template-card add the desired sensor, so that the card updates every time the sensor values change.

    entities:
      - input_select.hours_to_show
      - sensor.watts

Full config of the 1st post example:

type: vertical-stack
cards:
  - type: entities
    entities:
      - entity: input_select.hours_to_show
        name: Select Hours to Show
  - type: 'custom:config-template-card'
    variables:
      - 'states[''input_select.hours_to_show''].state'
    entities:
      - input_select.hours_to_show
      - sensor.watts
    card:
      type: history-graph
      entities:
        - entity: sensor.watts
          name: Watts
      hours_to_show: '${vars[0]}'
      refresh_interval: 0
3 Likes

Was REALLY happy about this until I found that the config-template-card doesn’t update live like the native cards wrapped in it (in my case, mini-graph-cards). The duration change reflects instantly contrary to one other report, but the sensors themselves don’t update anymore after that without another duration change or manual refresh :frowning:

Happy to be told I’m doing it wrong!

It’s wonderfull !!!
But my Apex graph don"t refresh when i change variable there is somethinf missing for that ?

Are you monitoring the entity?
You have to list all “sources” in the config-template-card entities section. Only then will the chart be updated.

type: custom:config-template-card
entities:
  - input_datetime.start_datetime
  - input_datetime.end_datetime
  - input_select.dropdown_wildcards
  - input_select.dropdown_entities
card:
.......
2 Likes

thanks it’s good for me, now i have make it with date :

type: custom:config-template-card
entities:
  - input_datetime.energy_viewer
variables:
  DAY: |
    {
    var targetDate = states['input_datetime.energy_viewer'].state;
    var myDate = states['input_datetime.energy_viewer'].state.split("-");
    var newDate = new Date( myDate[2], myDate[1] - 1, myDate[0]);  
    var offSet = Math.ceil((Date.parse(targetDate) - Date.now()) / 86400000)
    var sign = offSet < 0 ? "" : "+";
     sign + offSet +  "d" ;
    };
  TITLE: >
    var targetDate = states['input_datetime.energy_viewer'].state

    const options = { weekday: 'long', year: 'numeric', month: 'long', day:
    'numeric' };

    new Date(targetDate).toLocaleDateString("fr", options);
card:
  style: |
    #header__title {
      text-align: center;
    }
  type: custom:apexcharts-card

i have also make make it with date and read data from influxdb if anyone needs it

type: vertical-stack
cards:
  - type: entities
    entities:
      - entity: input_datetime.chart_datetime
        name: Start Zeit
      - entity: input_select.chart_span
        name: Dauer
  - type: custom:config-template-card
    entities:
      - input_datetime.chart_datetime
      - input_select.chart_span
    variables:
      DAY: >
        {

        var targetDate = states['input_datetime.chart_datetime'].state;

        var targetDate_ms = new Date(targetDate); 

        var Difference_In_ms = Date.now() - targetDate_ms

        var seconds = Math.floor((Difference_In_ms / 1000) % 60)

        var minutes = Math.floor((Difference_In_ms / (1000 * 60)) % 60)

        var hours = Math.floor((Difference_In_ms / (1000 * 60 * 60)) % 24)

        var days = Math.floor((Difference_In_ms / (1000 * 60 * 60 * 24)))

        var result = days < 0 ? "-1d" :
        "-"+days+"d"+"-"+hours+"h"+"-"+minutes+"m";
         result ;
        };
      span: states['input_select.chart_span'].state
    card:
      type: custom:apexcharts-card
      graph_span: ${span}
      span:
        start: minute
        offset: ${DAY}
      yaxis:
        - id: first
          decimals: 0
        - id: second
          opposite: true
      series:
        - entity: input_text.dummy
          yaxis_id: first
          type: line
          extend_to: false
          group_by:
            func: avg
            duration: 30min
          data_generator: |
            var params = new URLSearchParams({
                db: "home_assistant",
                p: "influxdbpasswort",
                u: "influxdbuser",
                q: "SELECT \"value\" FROM \"W\" WHERE \"entity_id\" = 'momentanp' AND time >= '" + start.toISOString() + "'AND time <= '" + end.toISOString() + "'"
                });

            var myInit = { method: 'GET',
                            headers: {
                                'Accept': 'application/json',
                            },
                            mode: 'cors',
                            cache: 'default' 
            };

            const request = async () => {
                var result = [];
                const response = await fetch('http://192.168.178.57:8086/query?' + params, myInit)
                const json = await response.json();
                if (json["results"] && json["results"][0] && json["results"][0]["series"]  && json["results"][0]["series"][0] && json["results"][0]["series"][0]["values"]) {
                    for(var val of json["results"][0]["series"][0]["values"]) {
                        result.push([new Date(val[0]), val[1]]);
                    }
                } 
                return result;
            }
            return request();
      update_interval: 5m

1 Like

Hey and WOW, that really works superb! :slight_smile: Thank you for your efforts!! I have two Questions:

Could it be possible to show the config-template-card AFTER the Data?

Is it possible to use just one config-template-card for two other Data-Cards, but the second Data is “outside” the vertical stack?

Sorry to bother you - Im really new here…