如何使用highcharts / d3.js或任何其他图表库绘制如下的折线图和条形图?
所以我要达到的目标是“如果在特定时间间隔内没有可用数据,则显示栏” (此处图表显示该时间间隔内无可用数据(17:30-18 :30))。
答案 0 :(得分:2)
您还可以将Highcharts与plotBands
功能一起使用(应该更具弹性)。在chart.events.load
上实现了一种算法,该算法检查null
中是否包含data
,并根据当前数据将绘图带动态添加到图表中。看一下这段代码:
load() {
var axis = this.xAxis[0]
var boundaries = []
var color = '#55f'
// Check there are nulls in data. If yes, save the boundaries.
data.forEach((elem, i) => {
if (elem === null) {
if (data[i-1]) { boundaries.push(data[i-1][0]) }
if (data[i+1]) { boundaries.push(data[i+1][0]) }
}
})
// Create plotBands basing on current boundaries.
boundaries.forEach((range, i) => {
if (i % 2) {
axis.addPlotBand({
from: boundaries[i-1],
to: range,
color: color
})
}
})
}
此外,您可以向图表添加其他系列(伪数据,数据为空),这将用于切换绘图带的可见性。这是代码:
{
// Fake series to add toggling visibility of plotbands functionality.
name: "Zone of Unavailability",
data: [],
events: {
legendItemClick() {
var bandsGroup = this.chart.xAxis[0].plotLinesAndBandsGroups['bands-0']
var bandsVisibility = bandsGroup.attr('opacity')
bandsGroup.attr({
opacity: bandsVisibility ? 0 : 1
})
}
}
}
实时示例: http://jsfiddle.net/dzj8bwLm/
API参考:
https://api.highcharts.com/highcharts/xAxis.plotBands https://api.highcharts.com/highcharts/series.line.events.legendItemClick
答案 1 :(得分:1)
您可以为此使用Highcharts / Highstock。您可以将线和列系列放入一个图表中,并根据需要进行操作。
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<div id="container" style="height: 400px; min-width: 600px"></div>
和
var data = [];
for (let i = 0; i < 100; i++) {
if (i == 10 || i == 11 || i == 12 || i == 13 || i == 14 || i == 15 || i == 16 || i == 17 || i == 18 || i == 27 || i == 28 || i == 29) {
data.push(null)
} else {
data.push([i, Math.floor((Math.random() * 100) + 1)])
}
}
Highcharts.stockChart('container', {
xAxis: {
ordinal: false,
labels: {
format: '{value}'
}
},
series: [{
data: data,
connectNulls: false,
dataGrouping: {
enabled: false
}
}, {
type: 'column',
pointWidth: 9,
dataGrouping: {
enabled: false
},
data: [
[10, 100],
[11, 100],
[12, 100],
[13, 100],
[14, 100],
[15, 100],
[16, 100],
[17, 100],
[18, 100],
[27, 100],
[28, 100],
[29, 100]
]
}]
});
观看此在线演示:jsFiddle