ApexCharts card - A highly customizable graph card

Hi there, I am new to Apex charts and try to limit the graph on the X-Axis to show up only when there is any data to display. So far I am only able to control this by hardcoding the graph span.
Is there any way to handle this dynamically based on the date from the data generator?

type: custom:apexcharts-card
graph_span: 12h
span:
  start: day
  offset: +7h

header:
  show: true
  title: Solar Prognose für heute
  show_states: false
  colorize_states: true
series:
  - entity: sensor.forecast_solar_power_estimate_watt_today
    type: line
    data_generator: |
      const sensorData = hass.states['sensor.forecast_solar_power_estimate_watt_today'].attributes.data;
      const data = [];
      
      // Iteriere über die Daten des Sensors und wandle die Timestamps um
      sensorData.forEach(item => {
        // Nur Daten verwenden, die einen Wert haben
        if (item.value > 0) {
          // Wandle den timestamp in Millisekunden um, da ApexCharts dies erwartet
          const timestamp = new Date(item.timestamp).getTime();
          
          // Wandle den Wert von Watt in Kilowatt um
          const valueInKW = item.value / 1000;

          // Füge die Daten im [timestamp, valueInKW] Format hinzu
          data.push([timestamp, valueInKW]);
        }
      });

      return data;

Hello,
Im trying to show temperature from last 365d, averaged by week.
It works fine with history stats:

But when im trying with apex it shows (my HA running only few weeks)

Is there any way to fulfill whole plot when there is no data?
(workaround is to set now graph span to 5week and increase it every week, but is any better solution?

Thanks bro! working good

1 Like

Confusing statement, you want data 365d ago and you only run since few weeks? If the latter then Apex shows correct and the other not

Does anyone managed to get it to take the full width in a Section’s dashboard. I didn’t managed to get it when taking the full 4 columns.

I’ve just discovered ApexCharts and after a bit of help if possible.

  1. Is there a way to change the current value shown to 2 decimal places.
    For example, the sensor value for gas is 0.74 but the chart shows 0.7

  2. Is there a way to use a “sensor” to define a “max” limit?
    For example:

Instead of:
max: 5

Use something like:
max: sensor.daily_energy_max

yml below:

type: custom:apexcharts-card
header:
 title: Used today
 show: true
 show_states: true
 colorize_states: true
chart_type: radialBar
apex_config:
 dataLabels:
   enabled: true
 legend:
   show: false
 update_interval: 5m
series:
 - entity: >-
     sensor.octopus_energy_electricity_XXXXXX_XXXXXX_current_accumulative_cost
   name: Electric
   unit: " GBP"
   group_by:
     func: last
     duration: 1d
   show:
     in_header: true
   min: 0
   max: 5
 - entity: >-
     sensor.octopus_energy_gas_XXXXXX_XXXXXX_current_accumulative_cost
   name: Gas
   unit: " GBP"
   group_by:
     func: last
     duration: 1d
   show:
     in_header: true
   min: 0
   max: 5

Hi,

I have a RESTful data sensor that’s populating an attribute with half hourly data for N numbers of days:

Currently looks like this (need to beautify it a bit as well, and reduce the overall height to around 250px ideally)
image

How do I show the high / low data as a datalabel, with just 1 instance per day? Is this possible with the way the data is being stored in the sensor’s attribute?

(Ideally I’d like to have shown this as a summary table per day (high/low) which is beyond an ApexChart question I think, and I wouldn’t know where to start with this!

Code:

type: custom:apexcharts-card
apex_config:
  chart:
    height: 300px
  xaxis:
    labels:
      style:
        colors: green
      datetimeFormatter:
                    year: 'ddd'
                    month: 'ddd'
                    day: 'ddd'
  dataLabels:
    offsetY: -5
    background:
      enabled: true
    style:
      colors:
        - rgba(0,0,0,0.4)
header:
  show: false
  show_states: true
  colorize_states: true
graph_span: 6d 
yaxis:
  - id: price
    min: 0
    decimals: 0
    apex_config:
      tickAmount: 8
stacked: false
span:
  start: hour
series:
  - entity: sensor.octopus_energy_electricity_XXXX_current_rate
    name: Actual Agile Import (current rate)
    transform: return x * 100;
    show:
      in_chart: false
    unit: p/kWh
  - entity: >-
      event.octopus_energy_electricity_XXXX_current_day_rates
    yaxis_id: price
    name: Actual Agile Import (current day)
    color: yellow
    opacity: 1
    stroke_width: 0
    extend_to: now
    type: column
    unit: p/kWh
    data_generator: |
      return entity.attributes.rates.map((entry) => {
         return [new Date(entry.start), entry.value_inc_vat*100];
       });     
    offset: "-15min"
    show:
      in_header: false
      legend_value: false
      offset_in_name: false
  - entity: event.octopus_energy_electricity_XXXX_next_day_rates
    yaxis_id: price
    name: Actual Agile Import (next day)
    color: cyan
    opacity: 1
    stroke_width: 2
    type: column
    unit: p/kWh
    data_generator: |
      return entity.attributes.rates.map((entry) => {
         return [new Date(entry.start), entry.value_inc_vat*100];
       });     
    offset: "-15min"
    show:
      in_header: false
      legend_value: false
      offset_in_name: false
      datalabels: false
  - entity: sensor.agile_predict
    yaxis_id: price
    name: Predicted Agile
    color: red
    opacity: 1
    stroke_width: 3
    extend_to: now
    unit: p/kWh
    data_generator: |
      return entity.attributes.prices.map((entry) => {
         return [new Date(entry.date_time), entry.agile_pred];
       });     
    offset: "-15min"
    show:
      in_header: false
      legend_value: false
      offset_in_name: false

(Code from: GitHub - fboundy/agile_predict)

1 Like

Managed to do it as simple as with header_color_threshold: true and then defining the tresholds.
Must have had some small mistyping at first when I tried it

Hi, I need help with a solar production forecast graph. I want the graph to show today’s forecast and today’s production to the Now point. And next for Now the forecast for tomorrow. I installed the Forecast.Solar integration. I have no idea if a data generator is needed. I don’t know how to proceed. Here is my code and chart

type: custom:apexcharts-card
header:
  show: true
  title: Solar forecast
  standard_format: true
  show_states: true
  colorize_states: true
apex_config:
  chart:
    height: 325px
  tooltip:
    enabled: true
    shared: true
    followCursor: true
graph_span: 4d
now:
  show: true
  label: Now
span:
  start: day
  offset: '-2day'
all_series_config:
  type: area
  opacity: 0.3
  stroke_width: 1
series:
  - entity: sensor.solax_battery_capacity
    name: Batrery
    float_precision: 0
    type: line
    color: '#f06292'
    opacity: 0.6
    yaxis_id: capacity
    extend_to: now
    show:
      legend_value: true
      in_header: false
    group_by:
      func: last
      duration: 5m
  - entity: sensor.solax_pv_power_total
    name: Solar power
    float_precision: 3
    color: '#ff9800'
    yaxis_id: kWh
    unit: kW
    transform: return x/1000;
    extend_to: now
    show:
      legend_value: true
      in_header: false
    group_by:
      func: avg
      duration: 5m
  - entity: sensor.energy_production_today
    name: Forecast today
    extend_to: false
    color: orange
    opacity: 0.3
    stroke_width: 0
    yaxis_id: kWh
    show:
      legend_value: false
      in_header: false
  - entity: sensor.energy_production_tomorrow
    name: Forecast tomorrow
    float_precision: 3
    extend_to: false
    color: grey
    opacity: 0.3
    stroke_width: 0
    yaxis_id: kWh
    show:
      legend_value: false
      in_header: false
  - entity: sensor.energy_production_today
    yaxis_id: header_only
    name: Forecast today
    color: orange
    show:
      legend_value: true
      in_header: true
      in_chart: false
  - entity: sensor.energy_production_today_remaining
    yaxis_id: header_only
    name: Forecast today remaining
    color: red
    show:
      legend_value: true
      in_header: true
      in_chart: false
  - entity: sensor.energy_production_tomorrow
    yaxis_id: header_only
    name: Forecast tomorrow
    color: grey
    show:
      legend_value: true
      in_header: true
      in_chart: false
yaxis:
  - id: capacity
    show: true
    opposite: true
    decimals: 0
    max: 100
    min: 0
    apex_config:
      tickAmount: 5
  - id: kWh
    show: true
    min: 0
    apex_config:
      tickAmount: 5
  - id: header_only
    show: false

To simplify my dashboards, I’d like to get rid of the one plotly-graph I have left in my setup by replacing it with Apex. The only thing that I am still unable to do is color the columns based on a specific attribute in the source data (electricity prices).

Visual to explain: at the top the current plotly chart, at the bottom the apex chart which should get the same coloring.

Using the color_threshold option is not feasible here (I think), as the three color thresholds vary per day based on the electricity prices of the day. BUT, each datapoint in the source sensor has the information available that’s needed.

Source sensor:

where tariff_group “low” means color “#00a964”, “normal” should translate to color “#227153” and “high” should translate to “#ed5e18”.

Complete apex config so far:

- type: custom:apexcharts-card
  graph_span: 18h
  header:
    title: Electricity Prices Today
    show: true
  span:
    start: hour
    offset: -3h
  now:
    show: true
    label: Now
  series:
    - entity: sensor.zonneplan_current_electricity_tariff
      type: column
      show:
        extremas: true
      float_precision: 3
      data_generator: |
        return entity.attributes.forecast.map((forecast, index) => {
          return [new Date(forecast["datetime"]).getTime() + 1800000, forecast.electricity_price / 10000000];
        });
  yaxis:
    - id: "1"
      min: ~0.1
      align_to: 0.1
      decimals: 2
      apex_config:
        title:
          text: €/kWh
        tickAmount: 3
  apex_config:
    xaxis:
      type: datetime
      tooltip:
        enabled: false
    chart:
      height: 320px

How can I generate the needed array of color codes for use with for instance apex_config.fill?

Hello
I m trying to add Axis title, when Using ~min and ~max

so to this:

I d like to add Y title. How to do that?

I have tried two approach, but wo success:

1)here max value ~250, doesnt work.


2)here i got error:

Is it possible to achieve a combo chart like this in Apex?

I currently have several area series, but would like to add a sensor that has boolean values (On/Off), and would love to display it as an area under the other lines.

Alternatively, if that’s not doable as the Y is dependent on other series, just to have a flat area showing how long heating has been on.

I’ve tried adding the entity as another area series, but it doesn’t seem to work.

card:
  type: custom:apexcharts-card
  header:
    show: true
    show_states: true
    colorize_states: false
    floating: true
  all_series_config:
    show:
      in_header: false
    stroke_width: 2
    type: area
    fill_raw: last
    opacity: 0.1
    extend_to: now
    group_by:
      func: avg
      duration: 30min
  graph_span: 24h
  span:
    start: day
  now:
    show: true
  apex_config:
    legend:
      position: top
      horizontalAlign: right
    grid:
      show: false
    yaxis:
      min: 14
      forceNiceScale: true
      tickAmount: 5
    annotations:
      yaxis:
        - "y": 21
          borderColor: "#fff"
          label:
            style:
              color: "#fff"
              background: "#00E396"
            text: Target 21C
  series:
    - entity: sensor.wiser_lts_temperature_living_room
      name: Living room
    - entity: sensor.wiser_lts_temperature_main_bedroom
      name: Bedroom
    - entity: sensor.wiser_lts_temperature_guest_bedroom
      name: Guests
    - entity: sensor.wiser_lts_temperature_kitchen
      name: Kitchen
    - entity: sensor.weather_station_temperature
      name: Bathroom
    - entity: sensor.outside_temperature
      name: Outside
      show:
        in_header: true
        in_chart: false
    - entity: sensor.wiser_boiler
      name: Boiler
    - entity: sensor.wiser_heating
      name: Heating

Hi,

I have 12 sensors with numeric values ​​in them corresponding to 12 months of data.
I want to make a graph line with the values ​​of each month.
I tried this:

type: custom:apexcharts-card
header:
  show: true
  title: Évolution
  show_states: true
  colorize_states: true
series:
  - entity: sensor.evolution_month_01
    data_generator: |
      const data = [];
      const now = new Date();
      const monthNames = ["Janv.", "Fév.", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Sept.", "Oct.", "Nov.", "Déc."];
      
      for (let i = 0; i < monthNames.length; i++) {
        const monthData = states['sensor.evolution_month_' + (i + 1)];

        const value = monthData && monthData.state ? parseFloat(monthData.state) : 0;
        const timestamp = new Date(now.getFullYear(), i, 1).getTime();
        data.push([timestamp, value]);
      }
      return data;

But the graph does not load, it remains “loading”.
Each sensor has a numeric value in it. Anyone have an idea?

Hello there,
I have 3 thermometers in my house that I would like to chart as 3 columns showing their current state. Since the entitys are refreshing their values at different times I cannot fix the graph_span to a fitting timewindow.
What would be the best way to show just 3 columns - one per entity - containing only the latest values?
I thought the series option ‘attribute’ would do the trick but cannot get any data from it.

My Entity looks like this:

series Options
Name	Type	Default	Since	Description
✅ entity	string		v1.0.0	The entity_id of the sensor to display
attribute	string		v1.4.0	Instead of retrieving the state, it will retrieve an attribute of the entity. Make sure you increase update_delay if the chart doesn't reflect the last value of the attribute

My yaml looks like this (not working right now):

type: custom:apexcharts-card
graph_span: 1h
layout: minimal
chart_type: line
series:
  - entity: sensor.thermometer_temperatur
    type: column
    attribute: state
  - entity: sensor.thermometer_vorlauf_fusbodenheizung_temperature
    type: column
    attribute: state
  - entity: sensor.thermostat_ausen_temperature
    type: column
    attribute: state

Is there an easy option doing this or do I have to fiddle around with some complicated data generator js?

Thank you for a fantastic card @RomRider.

Is there a way to use a leading currency symbol in the header rather than the trailing currency code?
Screenshot 2024-10-14 at 16.18.06

I’ve managed to do it for the Total displayed in the centre of the donut chart with the formatter, but have not been able to find a way to do it for the values displayed in the header.

type: custom:apexcharts-card
chart_type: donut
apex_config:
  dataLabels:
    formatter: |
      EVAL:function(value) {
        return value.toFixed(0) + " %";
      }
  plotOptions:
    pie:
      donut:
        labels:
          show: true
          total:
            show: true
            label: Total
            formatter: |
              EVAL:function(w) {
                return "R" + w.globals.seriesTotals.reduce((a, b) => {
                  return a + b;
                }, 0).toLocaleString('en-ZA', { minimumFractionDigits: 0, maximumFractionDigits: 0 }).replace(/\s/g, ',');
              }
header:
  title: Costs with EMS - Month-to-Date (from 1 Sep)
  floating: false
  standard_format: false
  show: true
  show_states: true
  colorize_states: true
series:
  - entity: sensor.standard_total_cost_import
    name: Standard
    float_precision: 0
    show:
      in_header: true
      datalabels: percent
      legend_value: false
  - entity: sensor.off_peak_total_cost_import
    name: Off-peak
    float_precision: 0
    show:
      in_header: true
      datalabels: percent
      legend_value: false
  - entity: sensor.peak_total_cost_import
    name: Peak
    float_precision: 0
    show:
      in_header: true
      datalabels: percent
      legend_value: false
  - entity: sensor.total_cost_import
    name: Total
    float_precision: 0
    unit: ""
    show:
      in_header: true
      in_chart: false
      datalabels: true

Hi bro, i use forecast solar. But line of pv forecast not show. My entity : sensor.energy_production_today ( kWh)

I am wondering where you have found this part cause I can not find that here in the documentation. I have searched for xaxis and found nothing at all.

Looks like that there is something more available and I am missing some features too like the font color in general which looks like greyish and I need black for family members with a limited vision that can nor see these kinds of grey even on big screens, I mean really big 50 inch monitors.

Therefore I am looking for some enhancements to make their life easier like here a navigation bar with colours that they had chosen for higher contrast and readability.
So far icon size and font size can not be changed.

This solution has been provided by the famous @Ildar_Gabdullin and makes their life with HA a lot easier. Again: those colors are their own choices which other might not like but with 1 eye left the world looks different and they can decide the best what works for them or not.

The HA version does mention that it can use the javascript lib. In some cases it works, not all and you need to be able to ‘translate’ to yaml
Installation & Getting Started – ApexCharts.js

1 Like

So I guess you had found there the axis description
and then inside that whole long description this

  axisBorder: {
      show: true,
      color: '#78909C',
      height: 1,
      width: '100%',
      offsetX: 0,
      offsetY: 0
  },

and you knew from the beginning that it must be part of the apex_config: section

apex_config:
  xaxis:
    axisborder:
      show: false
    axisTicks:
      show: false
    labels:
      show: false

and then you tried, right ?

For example this is a bit below you axisborder section and handles the axis title

      title: {
          text: undefined,
          offsetX: 0,
          offsetY: 0,
          style: {
              color: undefined,
              fontSize: '12px',
              fontFamily: 'Helvetica, Arial, sans-serif',
              fontWeight: 600,
              cssClass: 'apexcharts-xaxis-title',
          },

so I shoudl try to increase the font size this

apex_config:
  xaxis:
     title: 
       text: Test
       show: true
       style:
          color: blue
          fontSize: '12px'

And guess what ?

it really worked from the beginning.

Only issue for me how do I found out the objects which here is the chart title.

But what about the x-axis values / description like in this case “16. Okt.”
Is that a label ?

Trial and error… unless someone else knows about it

1 Like