使用Python-Flask向ChartJ传递日期值

2024-06-26 18:02:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要将Python Flask中的日期值传递到散点图的Chart JS。 当我像下面这样传递数据时,它不显示日期,而是将其视为一个表达式,并在X轴上显示一个数字。你知道吗

[{'x': '2009-03-19', 'y': 8.534092881859213e-05}, {'x': '2009-06-14', 'y': 0.00032793270435361847}, {'x': '2009-09-08', 'y': 0.00021380421032880591}, {'x': '2009-11-16', 'y': 0.0009079899617088027}, {'x': '2011-12-08', 'y': 0.0012405428762677923}, {'x': '2012-09-30', 'y': 0.0017202985101355472}]

以下是数据的外观:

[{'x': Timestamp('2009-03-19 00:00:00'), 'y': 8.534092881859213e-05}, {'x': Timestamp('2009-06-14 00:00:00'), 'y': 0.00032793270435361847}, {'x': Timestamp('2009-09-08 00:00:00'), 'y': 0.00021380421032880591}, {'x': Timestamp('2009-11-16 00:00:00'), 'y': 0.0009079899617088027}, {'x': Timestamp('2011-12-08 00:00:00'), 'y': 0.0012405428762677923}, {'x': Timestamp('2012-09-30 00:00:00'), 'y': 0.0017202985101355472}]

将数据传递到图表:

 return jsonify({'data':render_template('chart.html', 
                                               plotdata=data)})

绘图:

ds5=[]   
ds5.push ({      
fill: false,
showLine: true,
lineTension: 0.1,
backgroundColor: "red",
borderColor:  "red", // The main line color
borderCapStyle: 'square',
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "red",
pointBackgroundColor: "red",
pointBorderWidth: 1,
pointHoverRadius: 8,
pointHoverBackgroundColor: "yellow",
pointHoverBorderColor: "brown",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
// notice the gap in the data and the spanGaps: true
data :{{plotdata}},
spanGaps: true,
});       

var chartData5 = {
datasets : ds5
}

var holder = document.getElementById("myChart");
var ctx = document.getElementById("myChart").getContext("2d");

var myChart = new Chart(ctx, {
type: 'scatter',
data: chartData5,
options: {
title: {
display: true,
text: 'Decline Rate',
fontSize: 20,
fontFamily: 'verdana',
position: 'top',
fontStyle: 'bold',
fontColor: '#000066'
},
legend: {
display: false,
labels: {
usePointStyle: true,
},          
},
scales: {
xAxes: [{
display: true,
ticks: {
beginAtZero: true,
autoSkip: true,
autoSkipPadding: 30,
stepSize: 500,
maxTicksLimit: 10,
fontColor: '#000066'        
},
scaleLabel: {
display: true,
labelString: 'Date',
fontStyle: 'bold',
fontColor: '#000066'
}      
}],
yAxes: [{
display: true,
ticks: {
fontColor: '#000066'
},
scaleLabel: {
display: true,
labelString: 'Decline Coefficients',
fontStyle: 'bold',
fontColor: '#000066'
}
}]
}
}
});

有人能帮我把时间戳或日期值从flask传递到ChartJS吗


Tags: the数据truedatavardisplaychartred