我最近开始使用NVD3图表,并希望像Highcharts一样具有缩放选项。这是否可能?
有一个“带视图查找器的折线图”示例,使用nv.models.lineWithFocusChart()
。这种图表类型在主图表下方增加了一个“迷你地图”,您可以使用它来缩放和平移图表:
请参见:带视图查找器的折线图
function addZoom(options) {
// scaleExtent
var scaleExtent = 10;
// parameters
var yAxis = options.yAxis;
var xAxis = options.xAxis;
var xDomain = options.xDomain || xAxis.scale().domain;
var yDomain = options.yDomain || yAxis.scale().domain;
var redraw = options.redraw;
var svg = options.svg;
var discrete = options.discrete;
// scales
var xScale = xAxis.scale();
var yScale = yAxis.scale();
// min/max boundaries
var x_boundary = xScale.domain().slice();
var y_boundary = yScale.domain().slice();
// create d3 zoom handler
var d3zoom = d3.behavior.zoom();
// fix domain
function fixDomain(domain, boundary) {
if (discrete) {
domain[0] = parseInt(domain[0]);
domain[1] = parseInt(domain[1]);
}
domain[0] = Math.min(Math.max(domain[0], boundary[0]), boundary[1] - boundary[1]/scaleExtent);
domain[1] = Math.max(boundary[0] + boundary[1]/scaleExtent, Math.min(domain[1], boundary[1]));
return domain;
};
// zoom event handler
function zoomed() {
yDomain(fixDomain(yScale.domain(), y_boundary));
xDomain(fixDomain(xScale.domain(), x_boundary));
redraw();
};
// zoom event handler
function unzoomed() {
xDomain(x_boundary);
yDomain(y_boundary);
redraw();
d3zoom.scale(1);
d3zoom.translate([0,0]);
};
// initialize wrapper
d3zoom.x(xScale)
.y(yScale)
.scaleExtent([1, scaleExtent])
.on('zoom', zoomed);
// add handler
svg.call(d3zoom).on('dblclick.zoom', unzoomed);
};
// here chart is your nvd3 model
addZoom({
xAxis : chart.xAxis,
yAxis : chart.yAxis,
yDomain: chart.yDomain,
xDomain: chart.xDomain,
redraw : function() { chart.update() },
svg : svg
});