我使用顶点图从 json 输出中进行简单的数据可视化。我的图表基于纯 JavaScript,而不是 Vue 或其他框架。
我的 json (php) 后端创建两个 json 输出来绘制图表,如下所示
JSON 1
{
"x": "2019-05-27 16:18:48",
"y": "100"
},
{
"x": "2019-05-27 16:25:09",
"y": "110"
},
JSON 2
{
"x": "2019-05-27 16:18:48",
"y": "60"
},
{
"x": "2019-05-27 16:25:09",
"y": "65"
},
根据上述两个 json 输出,我检索数据并使用类别配对值方法绘制图表。下面是负责检索数据并绘制图表的代码。
获取json数据的函数
function data_function(){
$.ajax({
type: "Get",
url: backend,
data:{
param: "all_a"
},
async: true,
cache: false,
success: function(data) {
a_data = data;
$.ajax({
apex_task: "Get",
url: backend,
data:{
param: "all_b"
},
async: true,
cache: false,
success: function(data) {
b_data = data;
chart(a_data,b_data);
}
});
}
});
}
绘制图表函数
function draw_chart(a_data,b_data) {
var options = {
chart: {
height: 400,
type: 'bar',
stacked: false
},
series: [
{
name: 'a',
data: a_data,
},
{
name: 'b',
data: b_data,
}],
yaxis: [
{
axisTicks: {
show: true,
},
axisBorder: {
show: true,
color: '#008FFB'
},
labels: {
style: {
color: '#008FFB',
}
}
},
]
}
var chart = new ApexCharts(document.querySelector("#chartdiv"), options);
chart.render();
}
这工作正常,直到我第二次用新数据渲染图表。当我加载不同的数据而不重新加载 Windows 图表时,它会出现延迟并使用旧的不正确数据进行多次渲染。有时我必须多次运行 data_fnction 才能正确渲染图表。
我该如何解决这个问题?我需要使用像appendchart这样的函数吗?我如何使用我的 data_function
最佳答案
您应该在开始时只调用一次 render()
方法(即使数组为空也应该有效),然后在 ajax 调用中调用 updateSeries()
方法更新图表的数据。
var options = {
chart: {
height: 400,
type: 'bar',
stacked: false
},
series: [],
yaxis: [{
axisTicks: {
show: true,
},
axisBorder: {
show: true,
color: '#008FFB'
},
labels: {
style: {
color: '#008FFB',
}
}
}]
}
var chart = new ApexCharts(document.querySelector("#chartdiv"), options);
chart.render();
您的 ajax 调用图表的 updateSeries 方法
function data_function() {
$.ajax({
type: "Get",
url: backend,
data: {
param: "all_a"
},
async: true,
cache: false,
success: function (data) {
a_data = data;
$.ajax({
apex_task: "Get",
url: backend,
data: {
param: "all_b"
},
async: true,
cache: false,
success: function (data) {
b_data = data;
chart.updateSeries([{
name: 'a',
data: a_data
}, {
name: 'b',
data: b_data
}])
}
});
}
});
}
Docs对于updateSeries
关于javascript - Apexcharts 在渲染新系列之前删除旧数据系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56334249/