gpt4 book ai didi

javascript - Angular - 动态构建 JSON 以供图表师使用

转载 作者:行者123 更新时间:2023-11-29 10:33:36 25 4
gpt4 key购买 nike

我有一个 ionic 项目,正在使用以下库: http://gionkunz.github.io/chartist-js/index.html

真正绘制图表是通过以下实现的:

var chart = new Chartist.Line('.ct-chart', {
series: [
{
name: 'series-1',
data: [
{x: new Date(143134652600), y: 53},
{x: new Date(143234652600), y: 40},
{x: new Date(143340052600), y: 45},
{x: new Date(143366652600), y: 40},
{x: new Date(143410652600), y: 20},
{x: new Date(143508652600), y: 32},
{x: new Date(143569652600), y: 18},
{x: new Date(143579652600), y: 11}
]
},
{
name: 'series-2',
data: [
{x: new Date(143134652600), y: 53},
{x: new Date(143234652600), y: 35},
{x: new Date(143334652600), y: 30},
{x: new Date(143384652600), y: 30},
{x: new Date(143568652600), y: 10}
]
}
]
}, {
axisX: {
type: Chartist.FixedScaleAxis,
divisor: 5,
labelInterpolationFnc: function(value) {
return moment(value).format('MMM D');
}
}
});

使用 DIV:

  <div class="ct-chart ct-perfect-fourth"></div>

我不想使用如上所示的系列硬编码数组,而是希望通过函数调用动态构建它。

我可以如何做到这一点的任何例子?

谢谢!

最佳答案

您可以使用生成函数生成具有一点随机性和一些固定变量的数据。参数化图表的创建可能也更好,以便以后更容易重新创建。 Chartist 也有一个 update()可让您向其传递新数据和选项的函数,因此对此特别有用。

JSFIDDLE

Javascript

var button = document.getElementById('button');
var options = {
axisX: {
type: Chartist.FixedScaleAxis,
divisor: 5,
labelInterpolationFnc: function(value) {
return moment(value).format('MMM D');
}
}
};
var chart; // initialise the chart variable

function createChart(){
chart = new Chartist.Line('.ct-chart', changeData(), options);
}

function updateChart(){
chart.update(changeData());
}

function changeData(){
var series = [];
// set up series ranges
var numberOfSeries = 2;
var numberOfItems = 8;
var startDate = 143134652600;
var endDate = 143579652600;
var minY = 11;
var maxY = 53;
// creates the 'step' each x-axis item should take
var dateDiff = Math.floor((endDate - startDate) / numberOfItems);
// alternatively set the step to a whole day etc. (makes endDate unnecessary)
// var dateDiff = 24 * 60 * 60 * 1000;

for(var x = 0; x < numberOfSeries; x++){
var seriesData = [];
for(var y = 0; y < numberOfItems; y++){
seriesData.push({
x: new Date(startDate + (dateDiff*y)),
y: getRandomInt(minY, maxY)
})
}
series.push({
name: 'series-'+ (x+1),
data: seriesData
});
}
// return the data to display in the chart
return {series:series};
}

/**
* Returns a random integer between min (inclusive) and max (inclusive)
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}

button.addEventListener('click', updateChart);

createChart(); // generate chart initially

HTML

<button id="button">
Change Data
</button>
<div class="ct-chart ct-perfect-fourth"></div>

关于javascript - Angular - 动态构建 JSON 以供图表师使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40731365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com