简体   繁体   中英

multiple line charts with independent data Javascript (Chart.js or google-vizualisation)

js and I have two datasets:

data1 = [[0,1],[2,3],[5,7]] and data2 = [[1,4],[2,6],[5,2],[7,1]] for example. Each data list contains lists that represent points to plot on a same chart. (x and y values)

I want to plot exactely like this: https://www.chartjs.org/samples/latest/charts/line/multi-axis.html

But as you can see, my data lists don't have the same x or y values and they don't even have the same size, so I can't use the regular:

data: {labels = [1,2,3,4,5],
       data = [7,8,3,1,2],
       data = [9,1,2,3,4]}  //for example

How can I code this chart only with javascript (no jQuery please)? I didn't find anything on the Internet that might help. Any suggestions would matter to me !

You can use a scatter chart , that accepts the data as an array of objects containing x and y properties. To turn it into a line chart, define showLine: true inside the data configuration objects.

Given your data structures, the following line of code produces the data structure expected by Chart.js.

data1.map(o => ({ x: o[0], y: o[1] }))

Please have a look at below runnable code snippet.

 const data1 = [[0,1],[2,3],[5,7]]; const data2 = [[1,4],[2,6],[5,2],[7,1]]; new Chart('line-chart', { type: "scatter", responsive: true, data: { datasets: [ { data: data1.map(o => ({ x: o[0], y: o[1] })), label: 'Dataset 1', showLine: true, fill: false, borderColor: 'red' }, { data: data2.map(o => ({ x: o[0], y: o[1] })), label: 'Dataset 2', showLine: true, fill: false, borderColor: 'blue' } ] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script> <canvas id="line-chart" height="80"></canvas>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM