[Chartjs]-Dynamic chart.js not showing correctly

1👍

Change the type to time for xAxis in the options like this:

options: {
    scales: {
        xAxis: {
            type: "time",
            distribution: "linear"
        }
    }
}

Also, there’s something wrong with your code. The scales object is inside the plugins object. It should be inside options object.

Here is an example of a line chart with time as x-axis using your data:

const ctx = document.getElementById("myChart");

var chart = new Chart(ctx, {
    type: "line",
    data: {
        datasets:[
            {
                label: "Total all0",
                data: [{ "x": "2022-11-15 18:05:32", "y": 0.00476254 }, { "x": "2022-11-15 18:56:44", "y": 0.00476008 }, { "x": "2022-11-15 21:02:40", "y": 0.00473502 }, { "x": "2022-11-15 21:44:15", "y": 0.00473691 }, { "x": "2022-11-16 09:07:09", "y": 0.00478415 }, { "x": "2022-11-16 13:22:01", "y": 0.00472505 }, { "x": "2022-11-17 10:21:24", "y": 0.00474098 }, { "x": "2022-11-17 11:51:59", "y": 0.00470936 }, { "x": "2022-11-17 22:58:09", "y": 0.00469389 }, { "x": "2022-11-18 08:44:04", "y": 0.00470497 }],
                backgroundColor: "blue",
                borderColor: "blue",
            },
            {
                label: "Total all1",
                data: [{ "x": "2022-11-15 18:05:34", "y": 0 }, { "x": "2022-11-15 18:56:46", "y": 0 }, { "x": "2022-11-15 21:02:41", "y": 0 }, { "x": "2022-11-15 21:44:16", "y": 0 }, { "x": "2022-11-16 09:07:10", "y": 0 }, { "x": "2022-11-16 13:22:02", "y": 0 }, { "x": "2022-11-17 10:21:25", "y": 0 }, { "x": "2022-11-17 11:52:01", "y": 0 }, { "x": "2022-11-17 22:58:10", "y": 0 }, { "x": "2022-11-18 08:44:05", "y": 0 }],
                backgroundColor: "yellow",
                borderColor: "yellow",
            }
        ]
    },
    options: {
        scales: {
            xAxis: {
                type: "time",
                distribution: "linear",
                time: {
                    unit: "minute",
                    displayFormats: {
                        minute: "YYYY-MM-DD HH:mm:ss"
                    }
                }
            }
        }
    }
});
<div>
    <canvas id="myChart"></canvas>
</div>

<script src="https://cdn.jsdelivr.net/npm/moment@^2"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@^3"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@^1"></script>

Leave a comment