How to Set the Graph Span in ApexCharts

Hello everyone,

I’ve been working on integrating ApexCharts into my home automation setup, specifically for financial data visualization. I came across a challenge where I couldn’t dynamically update the chart’s timeframe using buttons. Each button is supposed to change the graph_span parameter, but the code wasn’t working as expected. After some research and trial and error, I found a solution that might help others facing similar issues.

The Problem:
I set up buttons that update a Text helper (input_text.timeframe) with values like 1h, 12h, etc. These values are valid for graph_span, but when I tried retrieving the value using {{ states('input_text.timeframe') }}, it didn’t update the chart. I even checked the developer tools, and the Text helper was correctly updating, but ApexCharts wasn’t responding.

The Solution:
After digging through forums and documentation, I realized that the issue was with how the state was being referenced. Instead of using {{ states('input_text.timeframe') }}, I needed to ensure that the state was being properly evaluated within the ApexCharts configuration. Here’s how I fixed it:

  1. Dynamic State Reference:
    • Use {{ states('input_text.timeframe') | string }} to ensure the state is correctly converted to a string.
  2. Update Trigger:
    • Add a watch function to trigger an update when the timeframe state changes.
  3. Configuration Update:
    • Modify the ApexCharts configuration to dynamically set the graph_span based on the timeframe state.

Here’s an example of how the updated configuration looks:

javascript
const chart = new ApexCharts(document.querySelector(“#chart”), {
// … other chart options
chart: {
type: ‘line’,
height: ‘500px’,
},
xaxis: {
type: ‘datetime’,
range: {
time: {
unit: ‘hour’,
value: parseInt(‘{{ states(‘input_text.timeframe’) | string }}’)
}
}
}
// … more options
});

// Watch for changes in the timeframe state
const timeframeWatch = () => {
const timeframe = ‘{{ states(‘input_text.timeframe’) | string }}’;
chart.updateOptions({
xaxis: {
range: {
time: {
unit: ‘hour’,
value: parseInt(timeframe)
}
}
}
});
};

// Trigger the update when the timeframe changes
timeframeWatch();

// Optional: Set an interval to periodically check for changes
setInterval(timeframeWatch, 60000);

Additional Tips:- Ensure that the graph_span values are compatible with ApexCharts’ time units (e.g., hour, day, week).- Test each button to confirm that the chart updates correctly.- If you’re using dynamic data, make sure your data source supports the selected timeframe.

**Conclusion:**This setup allows for a dynamic and user-friendly chart interface where users can easily switch between different timeframes. It’s been working smoothly for me, and I hope it helps others facing similar challenges!

Best regards,
[Your Name]