You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于当日价格占比配置ApexCharts柱状图颜色

解决Home Assistant中NordPool电价ApexCharts柱状图动态颜色问题

你当前用固定价格区间设置柱状图颜色的逻辑不够灵活,要实现按当日最高价占比动态变色,核心思路是在数据生成阶段先计算当日电价的最大值,再给每个小时的价格匹配对应颜色,具体修改如下:

修改后的完整配置代码

type: custom:apexcharts-card
graph_span: 36h
header:
  title: Energy price today (€/kWh)
  show: true
span:
  start: day
now:
  show: true
  label: Now
series:
  - entity: sensor.nordpool_energyprices
    type: column
    show:
      extremas: true
    float_precision: 2
    data_generator: |
      // 筛选当日的价格数据,用于计算当日最高价
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      const todayEnd = new Date(today);
      todayEnd.setHours(23, 59, 59, 999);
      
      const todayPrices = entity.attributes.prices.filter((price, index) => {
        const priceTime = new Date(entity.attributes.times[index]);
        return priceTime >= today && priceTime <= todayEnd;
      });
      
      // 计算当日最高价,加0.01防止所有价格为0时出现除以0错误
      const maxPrice = Math.max(...todayPrices, 0.01);
      
      // 遍历生成带颜色的数据点
      return entity.attributes.times.map((time, index) => {
        const price = entity.attributes.prices[index];
        const priceRatio = price / maxPrice;
        let color;
        
        // 按占比分配颜色,可自行调整比例和颜色值
        if (priceRatio >= 0.8) {
          color = 'red';
        } else if (priceRatio >= 0.6) {
          color = 'orange';
        } else {
          color = 'green';
        }
        
        // 返回ApexCharts支持的带颜色的数据格式
        return {
          x: new Date(time).getTime(),
          y: price,
          fillColor: color
        };
      });
yaxis:
  - decimals: 2
    apex_config:
      tickAmount: 10

关键逻辑说明

  • 筛选当日价格:先锁定当日的时间范围,从传感器属性中过滤出属于当日的电价,确保计算的最高价是当日的真实峰值,不会混入次日数据
  • 计算最高价:用Math.max提取当日价格的最大值,加0.01是为了避免所有价格为0时出现除以0的报错
  • 动态配色:每个价格除以最高价得到占比,按你需要的区间(80%+红色、60%-80%橙色、低于60%绿色)分配颜色,你可以直接在if-else里新增判断,扩展更多颜色档位
  • 数据格式:返回{x: 时间戳, y: 价格, fillColor: 颜色}的结构,ApexCharts会自动识别并应用每个柱子的填充色

内容的提问来源于stack exchange,提问作者Kaspars

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 07:31:10