javascript - 有限缩放的 d3 图

标签 javascript svg d3.js

我已经实现了一个 d3 线图,它从 CSV 文件中读取数据,然后绘制多条线以响应鼠标悬停事件。使用以下代码可以很好地进行平移和缩放(抱歉,它太长而且有点凌乱,但我觉得最好显示完整的代码):

    d3.csv("ijisb.csv", function(error, data) {

    var margin = {top: 50, right: 120, bottom: 50, left: 70},
    width = 1200 - margin.left - margin.right,
    height = 800 - margin.top - margin.bottom;

    var parseDate = d3.time.format("%m%d").parse;

    var color = d3.scale.category20();

    color.domain(d3.keys(data[0]).filter(function(key) { return key !== "date"; }));

    data.forEach(function(d) {
        d.date = parseDate(d.date);
    });

    var sources = color.domain().map(function(name) {
        return {
            name: name,
            values: data.map(function(d) {
                return {date: d.date, temperature: +d[name]};
            })
        };
    });

    var x = d3.time.scale()
        .range([0, width])
        .domain([
        d3.min(data, function(d) { return d.date; }),
        d3.max(data, function(d) { return d.date; })
    ]);

    var y = d3.scale.linear()
        .range([height, 0])
        .domain([
        0,
        d3.max(sources, function(c) { return d3.max(c.values, function(v) { return v.temperature; }); })
    ]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom")
        .ticks(12)
        .tickFormat(d3.time.format("%b %d"));

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left")
        .ticks(5);

    var line = d3.svg.line()
        .defined(function(d) { return d.temperature >= 0; })
        .x(function(d) { return x(d.date); })
        .y(function(d) { return y(d.temperature); });

    var zoom = d3.behavior.zoom()
    .x(x)
    .y(y)
    .scaleExtent([1, 8])
    .on("zoom", zoomed);

    var svg = d3.select("body").append("svg")
    .attr("width", "100%")
    .attr("height", "100%")
    .attr("viewBox", "0 0 1200 800")
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
    .call(zoom);

    var rect = svg.append("svg:rect")
    .attr("width", width)
    .attr("height", height)
    .attr("class", "plot");

    var make_x_axis = function () {
        return d3.svg.axis()
            .scale(x)
            .orient("bottom")
            .ticks(12)
            .tickFormat(d3.time.format("%b %d"));
    };

    var make_y_axis = function () {
        return d3.svg.axis()
            .scale(y)
            .orient("left")
            .ticks(5);
    };

    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

    svg.append("g")
        .attr("class", "y axis")
        .call(yAxis);

    svg.append("g")
        .attr("class", "x grid")
        .attr("transform", "translate(0," + height + ")")
        .call(make_x_axis()
        .tickSize(-height, 0, 0)
        .tickFormat(""));

    svg.append("g")
        .attr("class", "y grid")
        .call(make_y_axis()
        .tickSize(-width, 0, 0)
        .tickFormat(""));

    var source = svg.selectAll(".source")
    .data(sources)
    .enter().append("g")
    .attr("class", "source");

    var clip = svg.append("clipPath")
    .attr("id", "clip")
    .append("rect")
    .attr("x", 0)
    .attr("y", 0)
    .attr("width", width)
    .attr("height", height)
    .append("text");

    source.append("path")
        .data(sources)
        .attr("class", "line")
        .attr("clip-path", "url(#clip)")
        .attr("d", function(d) { return line(d.values); })
        .style("stroke", function(d) {return color(d.name);})
        .style("opacity", 0.8)
        .on("mouseover", function(d){
            d3.select(this)
                .style("stroke",function(d) {return color(d.name);})
                .style("opacity", 1.0)
                .style("stroke-width", 2.5);
                this.parentNode.parentNode.appendChild(this.parentNode);
            d3.select('#text-' + d.name)
                .style("fill",function(d) {return color(d.name);})
                .style("font-weight", 700);
        })
        .on("mouseout", function(d) {
            d3.select(this)
                .transition()
                .duration(250)
                .style("stroke", function(d) {return color(d.name);})
                .style("stroke-width", 1.5)
                .style("opacity", 0.8);
            d3.select('#text-' + d.name)
                .transition()
                .duration(250)
                .style("fill", function(d) {return color(d.name);})
                .style("font-weight", 400);
        })
        .attr("id", function(d, i) { return "path-" + d.name; }); 

    source.append("text")
        .datum(function(d) { return {name: d.name}; })
        .attr("x", function(d, i) { return width+10; })
        .attr("y", function(d, i) { return (i*(height/16)); })
        .style("fill", function(d) {return color(d.name);})
        .on("mouseover", function(d){
            d3.select('#path-' + d.name)
                .style("stroke",function(d) {return color(d.name);})
                .style("opacity", 1.0)
                .style("stroke-width", 2.5);
                this.parentNode.parentNode.appendChild(this.parentNode);
            d3.select(this)
                .style("fill",function(d) {return color(d.name);})
                .style("font-weight", 700);
        })
        .on("mouseout", function(d) {
            d3.select('#path-' + d.name)
                .transition()
                .duration(250)
                .style("stroke", function(d) {return color(d.name);})
                .style("stroke-width", 1.5)
                .style("opacity", 0.8);
            d3.select(this)
                .transition()
                .duration(250)
                .style("fill", function(d) {return color(d.name);})
                .style("font-weight", 400);
        })
        .text(function(d) { return d.name; })
        .attr("font-family","sans-serif")
        .attr("font-size","14px")
        .attr("id", function(d, i) { return "text-" + d.name; }
        ); 

    var minT = new Date('01/01/1900'), maxT = new Date('01/01/2002'), w = $(window).width();

function zoomed() {
        d3.event.translate;
        d3.event.scale;

    svg.select(".x.axis")
        .call(xAxis);
    svg.select(".y.axis").call(yAxis);
    svg.select(".x.grid")
        .call(make_x_axis()
        .tickSize(-height, 0, 0)
        .tickFormat(""));
    svg.select(".y.grid")
        .call(make_y_axis()
        .tickSize(-width, 0, 0)
        .tickFormat(""));
    source.select(".line")
        .attr("d", function(d) { return line(d.values); })
        .style("stroke", function(d) {return color(d.name);});  
    }

    });

我遇到的问题是我想限制平移和缩放,这样图形就不可能在屏幕外缩放或平移。我可以通过在缩放上设置 scaleExtent(在上面的示例中实现)并将缩放功能更改为:

    function zoomed() {

    var t = zoom.translate(),

    tx = t[0];
    ty = t[1];

    tx = Math.min(tx, 0);
    zoom.translate([tx, ty]);

    d3.event.translate;
    d3.event.scale;

    svg.select(".x.axis")
        .call(xAxis);
    svg.select(".y.axis").call(yAxis);
    svg.select(".x.grid")
        .call(make_x_axis()
        .tickSize(-height, 0, 0)
        .tickFormat(""));
    svg.select(".y.grid")
        .call(make_y_axis()
        .tickSize(-width, 0, 0)
        .tickFormat(""));
    source.select(".line")
        .attr("d", function(d) { return line(d.values); })
        .style("stroke", function(d) {return color(d.name);});
}

这将 x 轴的最小值限制为零。然而,无论我多么努力,我都无法限制 x 轴的最大值,这意味着图形仍然可以向右平移太远。

有什么帮助吗?我希望这是有道理的!

尼克

最佳答案

感谢帮助,最后我是通过下面的代码搞定的:

var t = zoom.translate(),
s = zoom.scale();

tx = Math.min(0, Math.max(width * (1 - s), t[0]));
ty = Math.min(0, Math.max(height * (1 - s), t[1]));

zoom.translate([tx, ty]);

难点在于在不同的缩放级别上限制图形,现在已经解决了。 d3.event.translate 和 d3.event.scale 语句也是不必要的,应该被删除。

关于javascript - 有限缩放的 d3 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16385490/

相关文章:

javascript - 类型错误 : Cannot set property 'state' of undefined

javascript - scope.data 没有 foreach 方法

php - svg 文件 phpstorm 的自动化 CSS Sprite

css - 有没有一种简单的方法来设置 svg 路径元素的样式,例如带有 3d 边框的 div?

javascript - 如何处理 d3.js 中丢失的数据

javascript - NavigationUrl 与在线 appSettings :***

javascript - 如何从选择菜单中删除选项?

javascript - D3 图形的缩放问题,适当缩放比例(Y 轴,X 轴)

javascript - D3 带有自定义元素 : TypeError: t is null

javascript - 圆圈标签未显示在 d3 数据可视化中