我有一个json数组,我在php中以...格式抓取。
[{"timestamp":"2018-05-30 00:33:05","temperature":"67.39","humidity":"66.57","pressure":"99.21"},{
我的网站上有一张highcharts图表......
<script>
$(function(){
$.getJSON('getdata.php?id=allTemp', function(json){
$('#container').highcharts({
series: [{
data: json
}],
title: {
text: 'Title'
}
})
})
})
</script>
<div id="container" style="width:100%; height:400px;"></div>
但没有任何图形,我是否需要为每个轴分配每个值?我的目标是在一个轴上有时间,在y轴上有其他3个值(温度,湿度和压力)。
答案 0 :(得分:0)
您需要设置不同的轴,将每个值分配给其中一个轴上的系列图形。由于这是一个相当普遍的问题,在不同的形状,我为你做了。使用示例JSON作为输入。
要点是:
datetime
,将日期转换为毫秒(因为这是highcharts接受的内容)。
var json = [{
"timestamp": "2018-05-30 00:33:05",
"temperature": "67.39",
"humidity": "66.57",
"pressure": "99.21"
}, {
"timestamp": "2018-05-30 00:35:05",
"temperature": "45.39",
"humidity": "69.57",
"pressure": "99.00"
}]
$(function() {
//create temporary arrays for each series
var temperature = [],
humidity = [],
pressure = [];
//loop through incoming json and push to respective series
$.each(json, function(i, el) {
let tmpTimestamp = new Date(el.timestamp).getTime() //get the millisecond representation of the timestamp
temperature.push({
x: tmpTimestamp,
y: parseFloat(el.temperature)
})
humidity.push({
x: tmpTimestamp,
y: parseFloat(el.humidity)
})
pressure.push({
x: tmpTimestamp,
y: parseFloat(el.pressure)
})
})
//Create array containing all series
var series = [{
name: 'Temperature',
data: temperature
}, {
name: 'Humidity',
data: humidity,
yAxis: '1'
}, {
name: 'Pressure',
data: pressure,
yAxis: '2'
}]
$('#container').highcharts({
series: series,
xAxis: {
type: 'datetime', //use the datetime type, so that highcharts knows the x-data is formatted by millisecond
minPadding: 0.1, //add some extra space on the left side of data
maxPadding: 0.1, //add some extra space on the right side of data
tickInterval: 1000 * 60 //one tick every 60 seconds
},
//give each series its own axis, colored the same as the series
yAxis: [{
id: '0',
title: {
text: 'Temperature',
style: {
color: Highcharts.getOptions().colors[0]
}
},
labels: {
format: '{value}°C',
style: {
color: Highcharts.getOptions().colors[0]
}
}
}, {
id: '1',
opposite: true,
title: {
text: 'Humidity',
style: {
color: Highcharts.getOptions().colors[1]
}
},
labels: {
format: '{value}%',
style: {
color: Highcharts.getOptions().colors[1]
}
}
}, {
id: '2',
opposite: true,
title: {
text: 'Pressure',
style: {
color: Highcharts.getOptions().colors[2]
}
},
labels: {
format: '{value}mb',
style: {
color: Highcharts.getOptions().colors[2]
}
}
}],
title: {
text: 'Title'
}
})
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/series-label.js"></script>
<div id="container" style: "min-width: 310px; max-width: 800px; height: 400px; margin: 0 auto"></div>
&#13;
JSFiddle示例: https://jsfiddle.net/dx9pntab/6/