Json文件数据到Chart.JS

nmpmafwu  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(196)

我尝试将json文件中的多个数据集添加到chart.JS中的行图表中。下面是我的JS代码:

const toCharts = () => {
    const jsonfiledata = { 
        jsonfileshort: {
            "0": 6516, "1": 5525, "2": 3351, "3": 3998, "4": 4228, "5": 4591, "6": 3482, "7": 3109, "8": 3205, "9": 3346
        },
        jsonfilelong: {
            "0": 42261,"1": 58953,"2": 59250,"3": 62787,"4": 74008,"5": 74976,"6": 66892,"7": 63223, "8": 71459, "9": 57387
        }
    }
    const AUDlinecharttop = document.getElementById('fxlinecharttopAUD').getContext('2d');
    const AUDlinechart1 = new Chart(AUDlinecharttop, {
        type: 'line',
        data: {
            labels: Object.keys(jsonfiledata),
            datasets: [{
                label: "Short",
                data: Object.values(jsonfileshort),
                backgroundColor: ['rgba(255, 99, 132, 0.2)'],
                borderColor: ['rgba(255, 99, 132, 1)'],
                borderWidth: 4,
            },
            { label: "Long" ,
                data: Object.values(jsonfilelong),
                backgroundColor: ['rgba(75, 192, 192, 0.2)'],
                borderColor: ['rgba(75, 192, 192, 1)'],
                borderWidth: 4
            }],
        },
        options: {
            responsive: "true",
            plugins: {
                title: {
                    color: "white",
                    display: true,
                    text: 'Positions (AUD)',
                },
                legend: {
                    display: true,
                    color: "white"
                }
            },
            maintainAspectRatio: false,
            elements: {
                line: {
                    fill: true,
                    tension: 0.2
                }
            },
            scales: {
                y: {
                    ticks: {
                        color: "white"
                    },
                    beginAtZero: true,
                },
                x: {
                    ticks: {
                        color: "white"
                    },
                    grid: {
                        display: false
                    }
                }
            }
        }
    });
}

以下是我的HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<canvas id="fxlinecharttopAUD"></canvas>

所有其他必要的HTML代码都被添加以使文件有效。这个代码有一些错误,我只是不能弄清楚,我可以使用图表来输入手动数据,但当谈到导入Json数据时,我卡住了。我已经阅读了太多其他的问答,但没有一个工作。提前感谢

q43xntqr

q43xntqr1#

您可以从错误消息中得知jsonfileshort未定义。
第一个

相关问题