首页 > 解决方案 > 同一页上有 2 个或更多图表?

问题描述

正如标题所说,我希望在同一页面上放置 2 个或更多图表,但每次我放置第二个时,第一个图表就会消失。添加 2 个或更多图表的正确方法是什么?

<!doctype html>
<html>

<head>
    <title>Twin</title>
        <script src="https://cdn.jsdelivr.net/npm/moment@2.24.0/min/moment.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
        <script src="https://cdn.jsdelivr.net/npm/hammerjs@2.0.8"></script>
        <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-zoom@0.7.0"></script>
        <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-streaming@1.8.0"></script>
    </head>

    <style>
        
        #myChart1 {
        position: relative;
        left: 25%;
        top: 25%;
        }

         #myChart2 {
        position: relative;
        left: 55%;
        top: 25%;
        }

        </style>


    <!--Charts-->

    <body>
        
    
        <div style="position: relative; height:100px; width:500px">
            <canvas id="myChart1" style="border: 1px solid #ccc"></canvas>
        </div>

        <div style="position: relative; height:100px; width:500px">
            <canvas id="myChart2" style="border: 1px solid #ccc"></canvas>
        </div>

        


    </div>


        <p>
            <!--
            <button id="randomizeData">Randomize Data</button>
            <button id="addDataset">Add Dataset</button>
            <button id="removeDataset">Remove Dataset</button>
            <button id="addData">Add Data</button>
            <button id="resetZoom">Reset Zoom</button> -->
        </p>
    </body>

<!--1-->

    <script>
        var chartColors = {
    red: 'rgb(255, 99, 132)',
    orange: 'rgb(255, 159, 64)',
    yellow: 'rgb(255, 205, 86)',
    green: 'rgb(75, 192, 192)',
    blue: 'rgb(54, 162, 235)',
    purple: 'rgb(153, 102, 255)',
    grey: 'rgb(201, 203, 207)'
};

function randomScalingFactor() {
    
    return (Math.random() > 0.5 ? 1.0 : -1.0) * Math.round(Math.random() * 100);
     
}

function onRefresh(chart) {
    chart.config.data.datasets.forEach(function(dataset) {
        dataset.data.push({
            x: Date.now(),
            y: randomScalingFactor()
        });
    });
}

var color = Chart.helpers.color;
var config = {
    type: 'line',
    data: {
        datasets: [{
            label: 'Schwingwert',
            backgroundColor: color(chartColors.blue).alpha(0.5).rgbString(),
            borderColor: chartColors.blue,
            fill: false,
            cubicInterpolationMode: 'monotone',
            data: []
        }]
    },
    options: {
        legend: {
            position: 'top'
        },
        title: {
            display: true,
            text: 'X Axis Zeitstempel (ms) / Y Axis Schwingungswert (m/sec)',
            position: 'top'
        },
        scales: {
            xAxes: [{
                type: 'realtime',
                scaleLabel:{
                    display: true,
                    labelString: 'Zeitstempel (ms)'
                },
                realtime: {
                    duration: 20000,
                    refresh: 1000,
                    delay: 2000,
                    onRefresh: onRefresh,
                }
            }],
            yAxes: [{
                type: 'linear',
                display: true,
                scaleLabel: {
                    display: true,
                    labelString: 'Amplitude (m/sec)'
                }
            }]
        },
        tooltips: {
            mode: 'nearest',
            intersect: false
        },
        hover: {
            mode: 'nearest',
            intersect: false
        },
        pan: {
            enabled: true,
            mode: 'x',
            rangeMax: {
                x: 4000
            },
            rangeMin: {
                x: 0
            }
        },
        zoom: {
            enabled: true,
            mode: 'x',
            rangeMax: {
                x: 20000
            },
            rangeMin: {
                x: 1000
            }
        }
    }
};

window.onload = function() {
    var ctx1 = document.getElementById('myChart1').getContext('2d');
    window.myChart = new Chart(ctx1, config);
};

document.getElementById('randomizeData').addEventListener('click', function() {
    config.data.datasets.forEach(function(dataset) {
        dataset.data.forEach(function(dataObj) {
            dataObj.y = randomScalingFactor();
        });
    });

    window.myChart.update();
});

var colorNames = Object.keys(chartColors);
document.getElementById('addDataset').addEventListener('click', function() {
    var colorName = colorNames[config.data.datasets.length % colorNames.length];
    var newColor = chartColors[colorName];
    var newDataset = {
        label: 'Dataset ' + (config.data.datasets.length + 1),
        backgroundColor: color(newColor).alpha(0.5).rgbString(),
        borderColor: newColor,
        fill: false,
        lineTension: 0,
        data: []
    };

    config.data.datasets.push(newDataset);
    window.myChart.update();
});

document.getElementById('removeDataset').addEventListener('click', function() {
    config.data.datasets.pop();
    window.myChart.update();
});

document.getElementById('addData').addEventListener('click', function() {
    onRefresh(window.myChart);
    window.myChart.update();
});

document.getElementById('resetZoom').addEventListener('click', function() {
    window.myChart.resetZoom();
});
    </script>




<!--2-->



<script>
    var chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};

function randomScalingFactor() {

return (Math.random() > 0.5 ? 1.0 : -1.0) * Math.round(Math.random() * 100);
 
}

function onRefresh(chart) {
chart.config.data.datasets.forEach(function(dataset) {
    dataset.data.push({
        x: Date.now(),
        y: randomScalingFactor()
    });
});
}

var color = Chart.helpers.color;
var config = {
type: 'line',
data: {
    datasets: [{
        label: 'Schwingwert',
        backgroundColor: color(chartColors.blue).alpha(0.5).rgbString(),
        borderColor: chartColors.blue,
        fill: false,
        cubicInterpolationMode: 'monotone',
        data: []
    }]
},
options: {
    legend: {
        position: 'top'
    },
    title: {
        display: true,
        text: 'X Axis Zeitstempel (ms) / Y Axis Schwingungswert (m/sec)',
        position: 'top'
    },
    scales: {
        xAxes: [{
            type: 'realtime',
            scaleLabel:{
                display: true,
                labelString: 'Zeitstempel (ms)'
            },
            realtime: {
                duration: 20000,
                refresh: 1000,
                delay: 2000,
                onRefresh: onRefresh,
            }
        }],
        yAxes: [{
            type: 'linear',
            display: true,
            scaleLabel: {
                display: true,
                labelString: 'Amplitude (m/sec)'
            }
        }]
    },
    tooltips: {
        mode: 'nearest',
        intersect: false
    },
    hover: {
        mode: 'nearest',
        intersect: false
    },
    pan: {
        enabled: true,
        mode: 'x',
        rangeMax: {
            x: 4000
        },
        rangeMin: {
            x: 0
        }
    },
    zoom: {
        enabled: true,
        mode: 'x',
        rangeMax: {
            x: 20000
        },
        rangeMin: {
            x: 1000
        }
    }
}
};

window.onload = function() {
var ctx2 = document.getElementById('myChart2').getContext('2d');
window.myChart = new Chart(ctx2, config);
};

document.getElementById('randomizeData').addEventListener('click', function() {
config.data.datasets.forEach(function(dataset) {
    dataset.data.forEach(function(dataObj) {
        dataObj.y = randomScalingFactor();
    });
});

window.myChart.update();
});

var colorNames = Object.keys(chartColors);
document.getElementById('addDataset').addEventListener('click', function() {
var colorName = colorNames[config.data.datasets.length % colorNames.length];
var newColor = chartColors[colorName];
var newDataset = {
    label: 'Dataset ' + (config.data.datasets.length + 1),
    backgroundColor: color(newColor).alpha(0.5).rgbString(),
    borderColor: newColor,
    fill: false,
    lineTension: 0,
    data: []
};

config.data.datasets.push(newDataset);
window.myChart.update();
});

document.getElementById('removeDataset').addEventListener('click', function() {
config.data.datasets.pop();
window.myChart.update();
});

document.getElementById('addData').addEventListener('click', function() {
onRefresh(window.myChart);
window.myChart.update();
});

document.getElementById('resetZoom').addEventListener('click', function() {
window.myChart.resetZoom();
});
</script>



</body>

</html>

你们有什么想法吗?可能我不在正确的轨道上!

我尝试了不同的 id 属性,但到目前为止它不起作用!

标签: javascripthtmlchartschart.js

解决方案


您的两个 JavaScript 块几乎相同(相同的配置、相同的功能等),我重构以澄清。

查找我的工作示例:Chart.js 在同一页面中的多个图表

初始化图表:

...
function onLoadOverride(chartId, config) {
    var ctx1 = document.getElementById(chartId).getContext("2d");
    new Chart(ctx1, config);
}
onLoadOverride("myChart1", config);
onLoadOverride("myChart2", config);
...

推荐阅读