# Using chart.js to create chart for daily prices

**URL:** https://discourse.nodered.org/t/using-chart-js-to-create-chart-for-daily-prices/86860
**Category:** Dashboard
**Tags:** chart
**Created:** [30 March 2024 08:22 UTC](https://discourse.nodered.org/t/using-chart-js-to-create-chart-for-daily-prices/86860 "2024-03-30T08:22:20Z")
**Posts on this page:** 19
**Page:** 1

<div class="post-metadata">

### Author: ![henrikj111](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/henrikj111/32/89645_2.png) [@henrikj111](https://discourse.nodered.org/u/henrikj111)
#### Post date: [30 March 2024 08:22 UTC](https://discourse.nodered.org/t/using-chart-js-to-create-chart-for-daily-prices/86860/1 "2024-03-30T08:22:20Z")

</div>

Hey, I'm new to Node red and trying to build a dashboard where one of the widgets is a chart that should display electricity prices from Nordpool's API (using node-red-contrib-nordpool-api-plus), updated daily with prices hour by hour from 00 to 23 for the entire day.

I'm processing the data in a function node to present it as "Hour" on the x-axis and "priceperkwh" on the y-axis for all hours of the upcoming day. My issue is that I can't code it so that "priceperkwh" updates with new values that I'm passing to my template. I've used this template to create the chart using chart.js HTML code.

As I mentioned, I'm a beginner and mainly using ChatGPT to create the code. But no matter how I instruct it, I can't come up with code that can receive and update the chart with new values. Does anyone know how I can solve this so that I have a chart that responds to the latest data I send from my function node?

Here's the date from my function-node:  
[{"hour":0,"pricePerKwh":55.47},{"hour":1,"pricePerKwh":56.01},{"hour":2,"pricePerKwh":55.99},{"hour":3,"pricePerKwh":57.13},{"hour":4,"pricePerKwh":60.21},{"hour":5,"pricePerKwh":62.79},{"hour":6,"pricePerKwh":63.9},{"hour":7,"pricePerKwh":65.89},{"hour":8,"pricePerKwh":63.63},{"hour":9,"pricePerKwh":60.35},{"hour":10,"pricePerKwh":52},{"hour":11,"pricePerKwh":36.18},{"hour":12,"pricePerKwh":37.14},{"hour":13,"pricePerKwh":18.39},{"hour":14,"pricePerKwh":23.46},{"hour":15,"pricePerKwh":50.55},{"hour":16,"pricePerKwh":74},{"hour":17,"pricePerKwh":81.75},{"hour":18,"pricePerKwh":82.94},{"hour":19,"pricePerKwh":78.96},{"hour":20,"pricePerKwh":74.75},{"hour":21,"pricePerKwh":71.27},{"hour":22,"pricePerKwh":65.99},{"hour":23,"pricePerKwh":60.73}]

Node-RED version: v3.1.8  
Node.js version: v20.11.1  
Darwin 23.4.0 arm64 LE  
Dashboard version 3.6.5 started at /ui

---

<div class="post-metadata">

### Author: ![jbudd](https://avatars.discourse-cdn.com/v4/letter/j/5f8ce5/32.png) [@jbudd](https://discourse.nodered.org/u/jbudd)
#### Post date: [30 March 2024 09:51 UTC](https://discourse.nodered.org/t/using-chart-js-to-create-chart-for-daily-prices/86860/2 "2024-03-30T09:51:25Z")

</div>

Edit: This reply relates to using the Node-red dashboard chart widget, not chart.js

> [@henrikj111](#):
>
> I'm processing the data in a function node to present it as "Hour" on the x-axis and "priceperkwh" on the y-axis for all hours of the upcoming day.

You need to send your data to the chart node in a specific format:  
An array containing a single object with properties "series", "data" and "labels".

- "series" is an array of the names of lines on the chart. For a single line, just one element in the array.
- "data" is an array of arrays, one array per line on the chart. Each array element is an object with x and y properties to define the points on the line.
- "labels" - Actually I'm not sure what labels does, but it is an array of strings, in my experience always an array of one element, an empty string.

```auto
[{
"series": ["Series Name"],
"data": [
    [{ "x": 1504029634400, "y": 7 },
     { "x": 1504029637959, "y": 7 },
     { "x": 1504029640317, "y": 7 }
    ]
],
"labels": [""]
}]

```

So I think your function should be generating this output, NB "x" and "y" not "hour" and "pricePerKwh"

```auto
[{
"series": ["Price Per KWh"],
"data": [
   [
    {"x":0,"y":55.47},{"x":1,"y":56.01},{"x":2,"y":55.99},{"x":3,"y":57.13},{"x":4,"y":60.21},{"x":5,"y":62.79},
    {"x":6,"y":63.9},{"x":7,"y":65.89},{"x":8,"y":63.63},{"x":9,"y":60.35},{"x":10,"y":52},{"x":11,"y":36.18},
    {"x":12,"y":37.14},{"x":13,"y":18.39},{"x":14,"y":23.46},{"x":15,"y":50.55},{"x":16,"y":74},{"x":17,"y":81.75},
    {"x":18,"y":82.94},{"x":19,"y":78.96},{"x":20,"y":74.75},{"x":21,"y":71.27},{"x":22,"y":65.99},{"x":23,"y":60.73}
  ]
],
"labels": [""]
}]

```

---

<div class="post-metadata">

### Author: ![henrikj111](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/henrikj111/32/89645_2.png) [@henrikj111](https://discourse.nodered.org/u/henrikj111)
#### Post date: [31 March 2024 18:09 UTC](https://discourse.nodered.org/t/using-chart-js-to-create-chart-for-daily-prices/86860/3 "2024-03-31T18:09:36Z")

</div>

Thanks for great help! While I was trying to figure out how to solve it, it seems I messed up somehow in Node red, because now I can't create charts by placing chart.js code in a template node. I've created multiple charts that way before, but now I just get a blank space where the chart should be visible. Any ideas on what I might have done...?

---

<div class="post-metadata">

### Author: ![henrikj111](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/henrikj111/32/89645_2.png) [@henrikj111](https://discourse.nodered.org/u/henrikj111)
#### Post date: [1 April 2024 14:51 UTC](https://discourse.nodered.org/t/using-chart-js-to-create-chart-for-daily-prices/86860/4 "2024-04-01T14:51:11Z")

</div>

Now I've got the function node processing the data so it looks right I think. But I can't seem to create a chart.js diagram with my template node. Do you see any obvious mistakes in my code?

```auto
<canvas id="myChart" width="400" height="400"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    var ctx = document.getElementById('myChart').getContext('2d');
    var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: msg.payload.labels,
            datasets: [{
                label: 'Price (SEK)',
                data: msg.payload.data[0],
                backgroundColor: 'rgba(255, 99, 132, 0.2)',
                borderColor: 'rgba(255, 99, 132, 1)',
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                x: {
                    type: 'category',
                    labels: msg.payload.labels
                },
                y: {
                    beginAtZero: true
                }
            }
        }
    });
</script>

```

Here's how my data looks now:  
{"series":["Price (SEK)"],"data":[[{"x":0,"y":466.41},{"x":1,"y":466.18},{"x":2,"y":461.8},{"x":3,"y":432.71},{"x":4,"y":421.17},{"x":5,"y":421.17},{"x":6,"y":425.67},{"x":7,"y":464.57},{"x":8,"y":489.03},{"x":9,"y":471.72},{"x":10,"y":432.71},{"x":11,"y":350.76},{"x":12,"y":208.22},{"x":13,"y":231.42},{"x":14,"y":115.77},{"x":15,"y":51.59},{"x":16,"y":47.55},{"x":17,"y":151.78},{"x":18,"y":391.39},{"x":19,"y":421.74},{"x":20,"y":370.96},{"x":21,"y":324.21},{"x":22,"y":48.01},{"x":23,"y":3.81}]],"labels":[""]}

---

<div class="post-metadata">

### Author: ![jbudd](https://avatars.discourse-cdn.com/v4/letter/j/5f8ce5/32.png) [@jbudd](https://discourse.nodered.org/u/jbudd)
#### Post date: [1 April 2024 14:59 UTC](https://discourse.nodered.org/t/using-chart-js-to-create-chart-for-daily-prices/86860/5 "2024-04-01T14:59:38Z")

</div>

As I put in my reply, my code relates to a chart using the node-ted-dashboard chart widget, not charts.js.

Apologies if that misled you.

But you could try feeding that data to a dashboard chart node!

---

<div class="post-metadata">

### Author: ![henrikj111](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/henrikj111/32/89645_2.png) [@henrikj111](https://discourse.nodered.org/u/henrikj111)
#### Post date: [1 April 2024 15:31 UTC](https://discourse.nodered.org/t/using-chart-js-to-create-chart-for-daily-prices/86860/6 "2024-04-01T15:31:19Z")

</div>

No problem, I actually suspected that, so I tried both the chart node and the template node. At first I figured I would use chart.js code to be able to customize the design more. But right now, I'm just happy if I can create a chart at all. If I use a chart node, do I need to set anything specific in the settings for it to receive the data correctly?

---

<div class="post-metadata">

### Author: ![KarolisL](https://avatars.discourse-cdn.com/v4/letter/k/a4c791/32.png) [@KarolisL](https://discourse.nodered.org/u/KarolisL)
#### Post date: [1 April 2024 16:11 UTC](https://discourse.nodered.org/t/using-chart-js-to-create-chart-for-daily-prices/86860/7 "2024-04-01T16:11:50Z")

</div>

You don't need to setup anything outside standard chart node to get data charted

I just want to point out that there is another option, alternative to chart.js - plotly.js which was nicely covered in

> [@Plotly - example charts](https://discourse.nodered.org/t/plotly-example-charts/30697):
>
> I've been playing with Plotly for a few days, and have received a lot of kind support from @bakman2, so would like to share what I've got so far, in case anyone else is interested. The complete flow as attached below. The usual way to install a 3rd party script/library is to create a static folder, install & run the script/library from there. However, in these examples there is no need to do this, as plotly.js is being loaded using a CDN and a ui-template node. [flow] In all 3 examples, the …

plotly allows more customization, so maybe you will find more success

---

<div class="post-metadata">

### Author: ![jbudd](https://avatars.discourse-cdn.com/v4/letter/j/5f8ce5/32.png) [@jbudd](https://discourse.nodered.org/u/jbudd)
#### Post date: [1 April 2024 16:20 UTC](https://discourse.nodered.org/t/using-chart-js-to-create-chart-for-daily-prices/86860/8 "2024-04-01T16:20:26Z")

</div>

> [@henrikj111](#):
>
> Any ideas on what I might have done...?

You are almost there. You have this

```auto
{"series":["Price (SEK)"],
"data":[
  [
    {"x":0,"y":466.41},{"x":1,"y":466.18},{"x":2,"y":461.8},{"x":3,"y":432.71},{"x":4,"y":421.17},
    {"x":5,"y":421.17},{"x":6,"y":425.67},{"x":7,"y":464.57},{"x":8,"y":489.03},{"x":9,"y":471.72},
    {"x":10,"y":432.71},{"x":11,"y":350.76},{"x":12,"y":208.22},{"x":13,"y":231.42}, 
    {"x":14,"y":115.77},{"x":15,"y":51.59},{"x":16,"y":47.55},{"x":17,"y":151.78},
    {"x":18,"y":391.39},{"x":19,"y":421.74},{"x":20,"y":370.96},{"x":21,"y":324.21},
    {"x":22,"y":48.01},{"x":23,"y":3.81}
  ]
],
"labels":[""]
}

```

And what you need is this

```auto
[
{"series":["Price (SEK)"],
"data":[
  [
    {"x":0,"y":466.41},{"x":1,"y":466.18},{"x":2,"y":461.8},{"x":3,"y":432.71},{"x":4,"y":421.17},
    {"x":5,"y":421.17},{"x":6,"y":425.67},{"x":7,"y":464.57},{"x":8,"y":489.03},{"x":9,"y":471.72},
    {"x":10,"y":432.71},{"x":11,"y":350.76},{"x":12,"y":208.22},{"x":13,"y":231.42}, 
    {"x":14,"y":115.77},{"x":15,"y":51.59},{"x":16,"y":47.55},{"x":17,"y":151.78},
    {"x":18,"y":391.39},{"x":19,"y":421.74},{"x":20,"y":370.96},{"x":21,"y":324.21},
    {"x":22,"y":48.01},{"x":23,"y":3.81}
  ]
],
"labels":[""]
}
]

```

> [@jbudd](#):
>
> **An array** containing a single object with properties "series", "data" and "labels".

---

<div class="post-metadata">

### Author: ![henrikj111](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/henrikj111/32/89645_2.png) [@henrikj111](https://discourse.nodered.org/u/henrikj111)
#### Post date: [1 April 2024 17:59 UTC](https://discourse.nodered.org/t/using-chart-js-to-create-chart-for-daily-prices/86860/9 "2024-04-01T17:59:33Z")

</div>

I think I've managed to get the data right now, but still nothing is showing up in my chart. I'm starting to wonder if there's something else fundamental that I've missed. Actually, I reinstalled the entire Node-RED yesterday because I was afraid I messed something up, so I should have a clean installation. This is how the data looks now:

```auto
[{"series":["Price (SEK)"],"data":[[{"x":0,"y":466.41},{"x":1,"y":466.18},{"x":2,"y":461.8},{"x":3,"y":432.71},{"x":4,"y":421.17},{"x":5,"y":421.17},{"x":6,"y":425.67},{"x":7,"y":464.57},{"x":8,"y":489.03},{"x":9,"y":471.72},{"x":10,"y":432.71},{"x":11,"y":350.76},{"x":12,"y":208.22},{"x":13,"y":231.42},{"x":14,"y":115.77},{"x":15,"y":51.59},{"x":16,"y":47.55},{"x":17,"y":151.78},{"x":18,"y":391.39},{"x":19,"y":421.74},{"x":20,"y":370.96},{"x":21,"y":324.21},{"x":22,"y":48.01},{"x":23,"y":3.81}]],"labels":[""]}]

```

And here's a screen shot of my chart node setting:

 ![image](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/9/b/9b49a509f7ce5288e29b5aeb5195e867e58d4b48.jpeg)

---

<div class="post-metadata">

### Author: ![henrikj111](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/henrikj111/32/89645_2.png) [@henrikj111](https://discourse.nodered.org/u/henrikj111)
#### Post date: [1 April 2024 18:01 UTC](https://discourse.nodered.org/t/using-chart-js-to-create-chart-for-daily-prices/86860/10 "2024-04-01T18:01:01Z")

</div>

That sounds interesting, I'll check it out!

---

<div class="post-metadata">

### Author: ![jbudd](https://avatars.discourse-cdn.com/v4/letter/j/5f8ce5/32.png) [@jbudd](https://discourse.nodered.org/u/jbudd)
#### Post date: [1 April 2024 18:11 UTC](https://discourse.nodered.org/t/using-chart-js-to-create-chart-for-daily-prices/86860/11 "2024-04-01T18:11:57Z")

</div>

> [@henrikj111](#):
>
> I think I've managed to get the data right now, but still nothing is showing up in my chart.

Your data works for me. Maybe you need to clear the chart by sending an empty array.  
Try this little flow.  
 ![image](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/3/c/3c9a74a2b1fbc54e2dc001d37a14b2ba995535b9.png)

```auto
[{"id":"90166590411864cf","type":"inject","z":"48c1acc20b51dbae","name":"Clear chart - empty array","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"[]","payloadType":"jsonata","x":290,"y":280,"wires":[["a65c8b5ae0d3f451"]]},{"id":"ef8e8528e41a4d6a","type":"template","z":"48c1acc20b51dbae","name":"Sample data","field":"payload","fieldType":"msg","format":"handlebars","syntax":"plain","template":"[{\"series\":[\"Price (SEK)\"],\n\"data\":[[{\"x\":0,\"y\":466.41},{\"x\":1,\"y\":466.18},{\"x\":2,\"y\":461.8},{\"x\":3,\"y\":432.71},{\"x\":4,\"y\":421.17},{\"x\":5,\"y\":421.17},{\"x\":6,\"y\":425.67},{\"x\":7,\"y\":464.57},{\"x\":8,\"y\":489.03},{\"x\":9,\"y\":471.72},{\"x\":10,\"y\":432.71},{\"x\":11,\"y\":350.76},{\"x\":12,\"y\":208.22},{\"x\":13,\"y\":231.42},{\"x\":14,\"y\":115.77},{\"x\":15,\"y\":51.59},{\"x\":16,\"y\":47.55},{\"x\":17,\"y\":151.78},{\"x\":18,\"y\":391.39},{\"x\":19,\"y\":421.74},{\"x\":20,\"y\":370.96},{\"x\":21,\"y\":324.21},{\"x\":22,\"y\":48.01},{\"x\":23,\"y\":3.81}]],\n\"labels\":[\"\"]}]","output":"json","x":390,"y":340,"wires":[["a65c8b5ae0d3f451"]]},{"id":"3225f48470de88ff","type":"inject","z":"48c1acc20b51dbae","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":240,"y":340,"wires":[["ef8e8528e41a4d6a"]]},{"id":"a65c8b5ae0d3f451","type":"ui_chart","z":"48c1acc20b51dbae","name":"","group":"9ecf53f701e0ff8d","order":0,"width":0,"height":0,"label":"chart","chartType":"line","legend":"false","xformat":"HH:mm:ss","interpolate":"linear","nodata":"","dot":false,"ymin":"","ymax":"","removeOlder":1,"removeOlderPoints":"","removeOlderUnit":"3600","cutout":0,"useOneColor":false,"useUTC":false,"colors":["#1f77b4","#aec7e8","#ff7f0e","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5"],"outputs":1,"useDifferentColor":false,"className":"","x":570,"y":340,"wires":[[]]},{"id":"9ecf53f701e0ff8d","type":"ui_group","name":"Default","tab":"4ee2829d80870ced","order":1,"disp":true,"width":"14","collapse":false,"className":""},{"id":"4ee2829d80870ced","type":"ui_tab","name":"Home","icon":"dashboard","disabled":false,"hidden":false}]

```

 ![image](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/c/f/cfec04c97ae9afd4dc93594c411d2a8a7aac033e.png)

---

<div class="post-metadata">

### Author: ![henrikj111](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/henrikj111/32/89645_2.png) [@henrikj111](https://discourse.nodered.org/u/henrikj111)
#### Post date: [1 April 2024 18:56 UTC](https://discourse.nodered.org/t/using-chart-js-to-create-chart-for-daily-prices/86860/12 "2024-04-01T18:56:33Z")

</div>

Thanks, that helped me move forward a bit. It seems like there's no need to clear the graph, but I noticed that the line chart works while the bar chart doesn't. Also, shouldn't the values on the x-axis be displayed as 00 - 23 as in the data? I redesigned the flow with my API node, but that shouldn't have any impact on the outcome, right?

```auto
[
    {
        "id": "04f2b53bc94d9038",
        "type": "function",
        "z": "f4eb22f2f5a36bf6",
        "name": "function 6",
        "func": "// Extract data from the incoming message\nvar data = msg.payload;\n\n// Initialize an array to hold the data for each hour\nvar hourlyData = Array.from({ length: 24 }, () => 0);\n\n// Loop through the data and accumulate prices for each hour\ndata.forEach(item => {\n var hour = new Date(item.timestamp).getHours();\n hourlyData[hour] += item.price; // Accumulate the price\n});\n\n// Create newData object in the desired format\nvar newData = {\n series: [\"Price (SEK)\"],\n data: [[]], // Array to hold the series data\n labels: [\"\"]\n};\n\n// Populate newData with hourly data\nhourlyData.forEach((price, hour) => {\n newData.data[0].push({ x: hour, y: price });\n});\n\n// Return the newData object as the output\nmsg.payload = [newData];\nreturn msg;\n\nreturn msg;",
        "outputs": 1,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 480,
        "y": 360,
        "wires": [
            [
                "bebed6a52e9b93e7",
                "75311bd3d841203b"
            ]
        ]
    },
    {
        "id": "e05a4f4652710d2c",
        "type": "inject",
        "z": "f4eb22f2f5a36bf6",
        "name": "",
        "props": [
            {
                "p": "payload"
            },
            {
                "p": "topic",
                "vt": "str"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "payload": "",
        "payloadType": "date",
        "x": 120,
        "y": 360,
        "wires": [
            [
                "82be1f996a22a720"
            ]
        ]
    },
    {
        "id": "82be1f996a22a720",
        "type": "nordpool-api-plus",
        "z": "f4eb22f2f5a36bf6",
        "name": "",
        "area": "SE3",
        "currency": "SEK",
        "action": "todayOrOverride",
        "x": 300,
        "y": 360,
        "wires": [
            [
                "04f2b53bc94d9038"
            ]
        ]
    },
    {
        "id": "bebed6a52e9b93e7",
        "type": "ui_chart",
        "z": "f4eb22f2f5a36bf6",
        "name": "",
        "group": "9ecf53f701e0ff8d",
        "order": 0,
        "width": 0,
        "height": 0,
        "label": "chart",
        "chartType": "line",
        "legend": "false",
        "xformat": "HH:mm",
        "interpolate": "linear",
        "nodata": "",
        "dot": false,
        "ymin": "",
        "ymax": "",
        "removeOlder": "24",
        "removeOlderPoints": "",
        "removeOlderUnit": "3600",
        "cutout": 0,
        "useOneColor": false,
        "useUTC": false,
        "colors": [
            "#1f77b4",
            "#aec7e8",
            "#ff7f0e",
            "#2ca02c",
            "#98df8a",
            "#d62728",
            "#ff9896",
            "#9467bd",
            "#c5b0d5"
        ],
        "outputs": 1,
        "useDifferentColor": false,
        "className": "",
        "x": 650,
        "y": 360,
        "wires": [
            []
        ]
    },
    {
        "id": "3be2ef53ac6fdabc",
        "type": "inject",
        "z": "f4eb22f2f5a36bf6",
        "name": "Clear chart - empty array",
        "props": [
            {
                "p": "payload"
            },
            {
                "p": "topic",
                "vt": "str"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "payload": "[]",
        "payloadType": "jsonata",
        "x": 450,
        "y": 440,
        "wires": [
            [
                "bebed6a52e9b93e7"
            ]
        ]
    },
    {
        "id": "75311bd3d841203b",
        "type": "debug",
        "z": "f4eb22f2f5a36bf6",
        "name": "debug 5",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "false",
        "statusVal": "",
        "statusType": "auto",
        "x": 660,
        "y": 460,
        "wires": []
    },
    {
        "id": "9ecf53f701e0ff8d",
        "type": "ui_group",
        "name": "Default",
        "tab": "4ee2829d80870ced",
        "order": 1,
        "disp": true,
        "width": "14",
        "collapse": false,
        "className": ""
    },
    {
        "id": "4ee2829d80870ced",
        "type": "ui_tab",
        "name": "Home",
        "icon": "dashboard",
        "disabled": false,
        "hidden": false
    }
]

```

 ![image](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/e/f/ef96c5e93f7c7a68bc2b81b700ea19f2351a7bd1.jpeg)

---

<div class="post-metadata">

### Author: ![smanjunath211](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/smanjunath211/32/95742_2.png) [@smanjunath211](https://discourse.nodered.org/u/smanjunath211)
#### Post date: [2 April 2024 00:44 UTC](https://discourse.nodered.org/t/using-chart-js-to-create-chart-for-daily-prices/86860/13 "2024-04-02T00:44:16Z")

</div>

have a look here too..

> [@Apex Chart with Customization](https://discourse.nodered.org/t/apex-chart-with-customization/77207):
>
> I spent most of my time last month in trying to find an alternative to ui\_chart in node-red-dashboard. the built in chart is good enough, the only drawback i faced was not having the zoom feature. so i was directed towards many alternatives but none of them had a simple and easy tutorial how to get the data from a mysql database and plot the same on dashboard. with the help of few experts, I could get the Apex chart start to look like what i wanted it to do. i am just putting a sample flow here…

```auto
[{"id":"dae53b72edc705e4","type":"ui_button","z":"58560d6d98cf8d06","name":"","group":"3c4ffa4110cd59c8","order":1,"width":"3","height":"1","passthru":false,"label":"Refresh","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"","payloadType":"str","topic":"topic","topicType":"msg","x":380,"y":3270,"wires":[["9747d50d74971dc9"]]},{"id":"9747d50d74971dc9","type":"change","z":"58560d6d98cf8d06","name":"","rules":[{"t":"set","p":"payload","pt":"msg","to":"[{\"x\":0,\"y\":466.41},{\"x\":1,\"y\":466.18},{\"x\":2,\"y\":461.8},{\"x\":3,\"y\":432.71},{\"x\":4,\"y\":421.17},{\"x\":5,\"y\":421.17},{\"x\":6,\"y\":425.67},{\"x\":7,\"y\":464.57},{\"x\":8,\"y\":489.03},{\"x\":9,\"y\":471.72},{\"x\":10,\"y\":432.71},{\"x\":11,\"y\":350.76},{\"x\":12,\"y\":208.22},{\"x\":13,\"y\":231.42},{\"x\":14,\"y\":115.77},{\"x\":15,\"y\":51.59},{\"x\":16,\"y\":47.55},{\"x\":17,\"y\":151.78},{\"x\":18,\"y\":391.39},{\"x\":19,\"y\":421.74},{\"x\":20,\"y\":370.96},{\"x\":21,\"y\":324.21},{\"x\":22,\"y\":48.01},{\"x\":23,\"y\":3.81}]","tot":"json"},{"t":"set","p":"payload","pt":"msg","to":"[\t {\t \"name\" : \"$/kWH\",\t \"data\" : payload.{\"x\": $.x, \"y\": $.y}\t }\t]\t","tot":"jsonata"},{"t":"set","p":"charttitle","pt":"msg","to":"Place Chart Title Here","tot":"str"}],"action":"","property":"","from":"","to":"","reg":false,"x":550,"y":3270,"wires":[["94892351e8e1ca4f","c1a4eeb3e69a1218"]]},{"id":"94892351e8e1ca4f","type":"ui_template","z":"58560d6d98cf8d06","group":"a2d9ac75438797b7","name":"Apex-Chart with Multiple Y Axis","order":1,"width":30,"height":"12","format":"<script src=\"https://cdn.jsdelivr.net/npm/apexcharts\"></script>\n<div id=\"chart\"></div>\n\n<script>\n\n(function(scope)\n {scope.$watch('msg', function(msg)\n {if (msg){var options =\n {series: msg.payload,\n chart:{type: 'area',stacked: false,height: 355,background:'#000',zoom:\n {type: 'x',enabled: true,autoScaleYaxis: true},\n toolbar:{autoSelected: 'zoom'}},\n dataLabels: {enabled: true,enabledOnSeries: [0],formatter: function (val, opts) {return val},},\n markers:{size: 2,},\n theme: {mode: 'dark'},\n colors: ['#FA2E2E', '#FAFA23', '#546E7A', '#E91E63', '#FF9800'],\n \n title: {text: msg.charttitle,align: 'center',margin: 10,offsetX: 0,offsetY: 0,floating: false,style: {fontSize:30,fontWeight: 'bold',fontFamily: undefined,color: 'yellow'},},\n stroke:{width: [8,0,2],curve: ['smooth', 'smooth', 'smooth']},\n yaxis:[\n {labels:{formatter: function (val){return val.toFixed(1);},},title: { text: \"Title-1\", style: {color: \"#FA2E2E\"}},},\n {labels:{formatter: function (val){return val.toFixed(1);},},title: { text: \"Title-2\", style: {color: \"#546E7A\"}},},],\n\n xaxis: {lines: {show: false,},type: 'gradient',datetimeUTC: false,labels: {format: 'dd/MMM HH:mm',},},\n tooltip: {enabled: true,style: {fontSize: '12px',fontFamily: undefined},x: {show: true,format: 'dd/MMM HH:mm',},\n row: {colors: undefined,opacity: 0.5},\n column: {colors: undefined,opacity: 0.5},\n padding: {top: 0,right: 0,bottom: 0,left: 0},},\n grid: {show: true,borderColor: '#ffffff',strokeDashArray: 0,position: 'back',\n xaxis: {lines: {show: false}}, \n yaxis: {lines: {show: false}},\n row: {colors: undefined,opacity: 0.5}, \n column: {colors: undefined,opacity: 0.5}, \n padding: {top: 0,right: 0,bottom: 0,left: 0},}};\n\n\nsetTimeout( ()=> {if(scope.chart){scope.chart.updateOptions(options)}else {scope.chart = new ApexCharts(document.querySelector(\"#chart\"), options);scope.chart.render();}}, 1000)}});})(scope);\n\n</script>","storeOutMessages":false,"fwdInMessages":false,"resendOnRefresh":false,"templateScope":"local","className":"","x":870,"y":3270,"wires":[[]]},{"id":"3c4ffa4110cd59c8","type":"ui_group","name":"VARIABLES","tab":"0a734ef04f43c77a","order":1,"disp":false,"width":"30","collapse":false,"className":""},{"id":"a2d9ac75438797b7","type":"ui_group","name":"CHART","tab":"0a734ef04f43c77a","order":2,"disp":false,"width":"30","collapse":false,"className":""},{"id":"0a734ef04f43c77a","type":"ui_tab","name":"APEX","icon":"dashboard","order":16,"disabled":false,"hidden":false}]

```

---

<div class="post-metadata">

### Author: ![henrikj111](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/henrikj111/32/89645_2.png) [@henrikj111](https://discourse.nodered.org/u/henrikj111)
#### Post date: [2 April 2024 13:03 UTC](https://discourse.nodered.org/t/using-chart-js-to-create-chart-for-daily-prices/86860/14 "2024-04-02T13:03:06Z")

</div>

Ok, one more step forward. With Vue, I can display a bar chart in Dashboard 1.0 but not in Dashboard 2.0. Is there any difference in how the template node is configured in 2.0, or should the code work in both versions?

```auto
[
    {
        "id": "1d4839b6d2163914",
        "type": "ui_template",
        "z": "c2ae6773200d3472",
        "group": "9ecf53f701e0ff8d",
        "name": "",
        "order": 3,
        "width": 0,
        "height": 0,
        "format": "<div id=\"app\">\n <canvas id=\"chartCanvas\" width=\"400\" height=\"400\"></canvas>\n</div>\n\n<script src=\"https://cdn.jsdelivr.net/npm/vue@2\"></script>\n<script src=\"https://cdn.jsdelivr.net/npm/chart.js@2\"></script>\n\n<script>\n (function() {\n var app = new Vue({\n el: '#app',\n mounted() {\n this.renderChart();\n },\n methods: {\n renderChart() {\n var ctx = document.getElementById('chartCanvas').getContext('2d');\n var myChart = new Chart(ctx, {\n type: 'bar',\n data: {\n labels: Array.from({ length: 24 }, (_, i) => i), // Skapar en lista med siffror från 0 till 23 för x-axeln\n datasets: [{\n label: 'Example Dataset',\n backgroundColor: '#f87979',\n data: [64.2, 14.83, 6.95, 9.73, 17.5, 81.24, 462.28, 589.76, 649.55, 542.59, 443.74, 455.44, 455.21, 444.66, 386.83, 290.88, 102.33, 477.46, 557.19, 529.03, 497.16, 453.82, 297.83, 19.24]\n }]\n },\n options: {\n responsive: true\n }\n });\n }\n }\n });\n})();\n</script>",
        "storeOutMessages": true,
        "fwdInMessages": true,
        "resendOnRefresh": true,
        "templateScope": "local",
        "className": "",
        "x": 140,
        "y": 400,
        "wires": [
            []
        ]
    },
    {
        "id": "9ecf53f701e0ff8d",
        "type": "ui_group",
        "name": "Default",
        "tab": "4ee2829d80870ced",
        "order": 1,
        "disp": true,
        "width": "14",
        "collapse": false,
        "className": ""
    },
    {
        "id": "4ee2829d80870ced",
        "type": "ui_tab",
        "name": "Home",
        "icon": "dashboard",
        "disabled": false,
        "hidden": false
    }
]

```

---

<div class="post-metadata">

### Author: ![Paul-Reed](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/paul-reed/32/66906_2.png) [@Paul-Reed](https://discourse.nodered.org/u/Paul-Reed)
#### Post date: [2 April 2024 18:30 UTC](https://discourse.nodered.org/t/using-chart-js-to-create-chart-for-daily-prices/86860/15 "2024-04-02T18:30:53Z")

</div>

> [@henrikj111](#):
>
> Is there any difference in how the template node is configured in 2.0

Yes major differences - read the documentation for help & examples - [Template ui-template | Node-RED Dashboard 2.0](https://dashboard.flowfuse.com/nodes/widgets/ui-template.html)

---

<div class="post-metadata">

### Author: ![henrikj111](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/henrikj111/32/89645_2.png) [@henrikj111](https://discourse.nodered.org/u/henrikj111)
#### Post date: [2 April 2024 19:31 UTC](https://discourse.nodered.org/t/using-chart-js-to-create-chart-for-daily-prices/86860/16 "2024-04-02T19:31:58Z")

</div>

Sure, I'll have another look. Is there anything specific in the instructions you think I should focus on to solve my issue with displaying charts in my template node?

---

<div class="post-metadata">

### Author: ![joepavitt](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/joepavitt/32/59722_2.png) [@joepavitt](https://discourse.nodered.org/u/joepavitt)
#### Post date: [3 April 2024 18:11 UTC](https://discourse.nodered.org/t/using-chart-js-to-create-chart-for-daily-prices/86860/17 "2024-04-03T18:11:44Z")

</div>

You are using the input formatted for a Dashboard 1.0 chart, but you're using Dashboard 2.0.

If you set your `msg.topic` to be your series name (as you have configured on the chart) and then `msg.payload` to equal what you currently have as `msg.payload.data` then it should work

---

<div class="post-metadata">

### Author: ![henrikj111](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/henrikj111/32/89645_2.png) [@henrikj111](https://discourse.nodered.org/u/henrikj111)
#### Post date: [6 April 2024 11:25 UTC](https://discourse.nodered.org/t/using-chart-js-to-create-chart-for-daily-prices/86860/18 "2024-04-06T11:25:20Z")

</div>

> [@joepavitt](#):
>
> If you set your `msg.topic` to be your series name (as you have configured on the chart) and then `msg.payload` to equal what you currently have as `msg.payload.data` then it should work

I'm still struggling with my graphs. I think I managed to change the code as you suggested. But there's something weird with my dashboard. I've managed to display one graph with hardcoded values in a template node. But I can't publish any other graphs, not even if I copy the working node and add it to the dashboard with a unique canvas id. I don't know how many 100 graphs I've tried that just show a blank area, so I'm starting to suspect that something else is wrong than just the code for my graphs. I appreciate any help I can get!

This is what my template node looks like now:

```auto
<template>
  <div>
    <canvas id="priceChart" width="800" height="400"></canvas>
  </div>
</template>

<script>
import Chart from 'chart.js/auto';

export default {
  mounted() {
    // Kalla på renderChart vid montering
    this.renderChart();
  },
  props: ['chartData'], // Definiera en prop för att ta emot data från överordnad komponent
  methods: {
    renderChart() {
      // Hämta canvas-elementet för diagrammet
      var ctx = document.getElementById('priceChart').getContext('2d');

      // Skapa ett nytt diagram med Chart.js
      var priceChart = new Chart(ctx, {
        type: 'bar', // Typ av diagram är stapeldiagram
        data: {
          // Data för diagrammet
          labels: msg.payload.labels, // Skapa labels för timmarna 0 till 23
          datasets: [{
            label: 'Price (SEK)', // Etikett för dataserien
            data: msg.payload.data, // Använd den mottagna datan för y-värdena
            backgroundColor: 'rgb(75, 192, 192)', // Bakgrundsfärg för staplarna
            borderColor: 'rgb(54, 162, 235)', // Kantfärg för staplarna
            borderWidth: 1 // Bredd på kanten för staplarna
          }]
        },
        options: {
          responsive: true, // Göra diagrammet responsivt
          scales: {
            x: {
              title: {
                display: true,
                text: 'Hour of the day' // Text för x-axeln
              }
            },
            y: {
              title: {
                display: true,
                text: 'Price (SEK)' // Text för y-axeln
              },
              beginAtZero: true // Börja y-axeln vid noll
            }
          }
        }
      });
    }
  }
};
</script>

<style>
/* Här kan du lägga till CSS-stilar om det behövs */
</style>

```

---

<div class="post-metadata">

### Author: ![joepavitt](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/joepavitt/32/59722_2.png) [@joepavitt](https://discourse.nodered.org/u/joepavitt)
#### Post date: [6 April 2024 16:28 UTC](https://discourse.nodered.org/t/using-chart-js-to-create-chart-for-daily-prices/86860/19 "2024-04-06T16:28:07Z")

</div>

Your running your renderChart on mounted, i.e. when the chart first renders, at that point though, there is no data available in `msg.payload` until a new message is received.

You'd be best off defining your Chart structure, etc, then add a socket listener for watching msg-input and then add your fata to the chart accordinlgy
