【问题标题】:d3 brush and clipPath: Main chart outside boundsd3画笔和clipPath:主图表边界外
【发布时间】:2018-07-08 17:28:16
【问题描述】:

我正在尝试使用画笔组件(基于https://bl.ocks.org/SevenChan07/495cd567e0ede0deeb14bb3599dce685)并使用输入-合并-退出模式制作条形图,但我无法使画笔正常工作。当我移动画笔时,图表超出了它的界限。我可能与剪辑有关,但我不知道如何解决。

var defs = focus.append('defs');

// use clipPath
defs.append('clipPath')
    .attr('id', 'my-clip-path')
    .append('rect')
    .attr('width', width)
    .attr('height', height);

任何帮助将不胜感激。

这里是fiddle,下面是sn-p:

let barData = []
for(let i = 0;i < 100; i++){
  barData.push({
    Prob: Math.random()*10,
    labels: 'test' + i
  })
}

barchart(barData)
    
    
function barchart(data) {

    var ordinals = data.map(function (d) {
        return d.labels;
    });


    var svg = d3.select("#myPlot").select("svg");
    var margin = {
            top: 20,
            right: 20,
            bottom: 0.3 * svg.attr("height"),
            left: 40
        },
        width = +svg.attr("width") - margin.left - margin.right,
        height = +svg.attr("height") - margin.top - margin.bottom,
        margin2 = {
            top: 20 + margin.top + height,
            right: 20,
            bottom: 30,
            left: 40
        },
        height2 = height / 5;

    // the scale
    var scale = {
        x: d3.scaleLinear().range([0, width]).nice(),
        x2: d3.scaleLinear().range([0, width]).nice(),
        y: d3.scaleLinear().range([height, 0]).nice(),
        y2: d3.scaleLinear().range([height2, 0]).nice()
    };

    let xBand = d3.scaleBand().domain(d3.range(-1, ordinals.length)).range([0, width])

    var axis = {
        x: d3.axisBottom(scale.x).tickFormat((d, e) => ordinals[d]),
        y: d3.axisLeft(scale.y)
    };

    var brush = d3.brushX()
        .extent([[0, 0], [width, height2]])
        .on("brush", brushed)


    var focus = svg.select('.focus')
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    focus.select(".axis").attr("transform", "translate(0," + height +")");

    var context = svg.select('.context')
        .attr("transform", "translate(" + margin2.left + "," + margin2.top + ")");


    var defs = focus.append('defs');

    // use clipPath
    defs.append('clipPath')
        .attr('id', 'my-clip-path')
        .append('rect')
        .attr('width', width)
        .attr('height', height);

    function updateScales(data) {
        scale.x.domain([-1, ordinals.length])
        scale.y.domain([0, d3.max(data, d => d.Prob)])
        scale.x2.domain(scale.x.domain())
        scale.y2.domain([0, d3.max(data, d => d.Prob)])
    }


    svg.call(renderPlot, data)

    function renderPlot(selection, data) {
        updateScales(data);

        selection.select(".context")
            .attr("transform", "translate(" + margin2.left + "," + margin2.top + ")")
            .select('.brush')
            .call(brush)
            .call(brush.move, scale.x.range())

        selection.select(".axis2")
            .attr("transform", "translate(0," + height2 +")");

        selection.select(".focus").select(".axis").call(axis.x);
        selection.select(".focus").select(".axis.axis--y").call(axis.y);

        selection
            .call(renderPoints, data);
    }


    function renderPoints(selection, data) {
        
        var points = selection.select('.focus')
          	.selectAll('.bar').data(data);

        var newPoints = points.enter().append('rect')
            .attr('class', 'bar')
            .attr('x', (d, i) => {
                return scale.x(i) - xBand.bandwidth() * 0.9 / 2
            })
            .attr('y', (d, i) => {
                return scale.y(d.Prob)
            })
            .attr('width', xBand.bandwidth() * 0.9)
            .attr('height', d => {
                return height - scale.y(d.Prob)
            });

        points.merge(newPoints)
            .transition().duration(1000)
            .attr('x', (d, i) => {
                return scale.x(i) - xBand.bandwidth() * 0.9 / 2
            })
            .attr('y', (d, i) => {
                return scale.y(d.Prob)
            })
            .attr('width', xBand.bandwidth() * 0.9)
            .attr('height', d => {
                return height - scale.y(d.Prob)
            });

        points.exit()
            .transition().duration(1000)
            .remove();


        var sPoints = selection.select('.context').selectAll('.bar').data(data);

        var newsPoints = sPoints.enter().append('rect')
            .attr('class', 'bar')
            .attr('x', (d, i) => {
                return scale.x2(i) - xBand.bandwidth() * 0.9 / 2
            })
            .attr('y', (d, i) => scale.y2(d.Prob))
            .attr('width', xBand.bandwidth() * 0.9)
            .attr('height', d => {
                return height2 - scale.y2(d.Prob)
            });

        sPoints.merge(newsPoints)
            .transition().duration(1000)
            .attr('x', (d, i) => {
                return scale.x2(i) - xBand.bandwidth() * 0.9 / 2
            })
            .attr('y', (d, i) => scale.y2(d.Prob))
            .attr('width', xBand.bandwidth() * 0.9)
            .attr('height', d => {
                return height2 - scale.y2(d.Prob)
            });

        sPoints.exit()
            .transition().duration(1000)
            .remove();



    }


    function brushed() {
        var s = d3.event.selection || scale.x2.range()
        scale.x.domain(s.map(scale.x2.invert, scale.x2))
        focus.select('.axis').call(axis.x)
        focus.selectAll('.bar')
            .attr('x', (d, i) => {
                return scale.x(i) - xBand.bandwidth() * 0.9 / 2
            })
    }


}
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
    <style type="text/css">
        .bar { fill: steelblue; }
    </style>

<script src='https://d3js.org/d3.v4.min.js' type='text/javascript'></script>


</head>
<body>
  <div class='chart span4' id='myPlot'>
    <svg width="700" height="500">
      <g class="focus">
        <g class="axis"></g>
        <g class="axis axis--y"></g>
      </g>
      <g class="context">
        <g class="axis2"></g>
        <g class="brush"></g>
      </g>
    </svg>
   </div>
</body>
</html>

【问题讨论】:

    标签: javascript d3.js


    【解决方案1】:

    您几乎完成了,您只需要将剪辑路径应用到某个东西上。我们可以很容易地用你的酒吧做到这一点(你也可以使用包含 only 酒吧的g):

    var newPoints = points.enter().append('rect')
       .attr('class', 'bar')
       .....  // other attributes
       .attr("clip-path","url(#my-clip-path)");
    

    我们只需要在输入时执行此操作,因为不需要更新剪辑路径(我们不会更改它)。下面是一个sn-p:

    let barData = []
    for(let i = 0;i < 100; i++){
      barData.push({
        Prob: Math.random()*10,
        labels: 'test' + i
      })
    }
    
    barchart(barData)
        
        
    function barchart(data) {
    
        var ordinals = data.map(function (d) {
            return d.labels;
        });
    
    
        var svg = d3.select("#myPlot").select("svg");
        var margin = {
                top: 20,
                right: 20,
                bottom: 0.3 * svg.attr("height"),
                left: 40
            },
            width = +svg.attr("width") - margin.left - margin.right,
            height = +svg.attr("height") - margin.top - margin.bottom,
            margin2 = {
                top: 20 + margin.top + height,
                right: 20,
                bottom: 30,
                left: 40
            },
            height2 = height / 5;
    
        // the scale
        var scale = {
            x: d3.scaleLinear().range([0, width]).nice(),
            x2: d3.scaleLinear().range([0, width]).nice(),
            y: d3.scaleLinear().range([height, 0]).nice(),
            y2: d3.scaleLinear().range([height2, 0]).nice()
        };
    
        let xBand = d3.scaleBand().domain(d3.range(-1, ordinals.length)).range([0, width])
    
        var axis = {
            x: d3.axisBottom(scale.x).tickFormat((d, e) => ordinals[d]),
            y: d3.axisLeft(scale.y)
        };
    
        var brush = d3.brushX()
            .extent([[0, 0], [width, height2]])
            .on("brush", brushed)
    
    
        var focus = svg.select('.focus')
            .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
    
        focus.select(".axis").attr("transform", "translate(0," + height +")");
    
        var context = svg.select('.context')
            .attr("transform", "translate(" + margin2.left + "," + margin2.top + ")");
    
    
        var defs = focus.append('defs');
    
        // use clipPath
        defs.append('clipPath')
            .attr('id', 'my-clip-path')
            .append('rect')
            .attr('width', width)
            .attr('height', height);
    
        function updateScales(data) {
            scale.x.domain([-1, ordinals.length])
            scale.y.domain([0, d3.max(data, d => d.Prob)])
            scale.x2.domain(scale.x.domain())
            scale.y2.domain([0, d3.max(data, d => d.Prob)])
        }
    
    
        svg.call(renderPlot, data)
    
        function renderPlot(selection, data) {
            updateScales(data);
    
            selection.select(".context")
                .attr("transform", "translate(" + margin2.left + "," + margin2.top + ")")
                .select('.brush')
                .call(brush)
                .call(brush.move, scale.x.range())
    
            selection.select(".axis2")
                .attr("transform", "translate(0," + height2 +")");
    
            selection.select(".focus").select(".axis").call(axis.x);
            selection.select(".focus").select(".axis.axis--y").call(axis.y);
    
            selection
                .call(renderPoints, data);
        }
    
    
        function renderPoints(selection, data) {
            
            var points = selection.select('.focus')
              	.selectAll('.bar').data(data);
    
            var newPoints = points.enter().append('rect')
                .attr('class', 'bar')
                .attr('x', (d, i) => {
                    return scale.x(i) - xBand.bandwidth() * 0.9 / 2
                })
                .attr('y', (d, i) => {
                    return scale.y(d.Prob)
                })
                .attr('width', xBand.bandwidth() * 0.9)
                .attr('height', d => {
                    return height - scale.y(d.Prob)
                })
                .attr("clip-path","url(#my-clip-path)");
    
            points.merge(newPoints)
                .transition().duration(1000)
                .attr('x', (d, i) => {
                    return scale.x(i) - xBand.bandwidth() * 0.9 / 2
                })
                .attr('y', (d, i) => {
                    return scale.y(d.Prob)
                })
                .attr('width', xBand.bandwidth() * 0.9)
                .attr('height', d => {
                    return height - scale.y(d.Prob)
                })
                
    
            points.exit()
                .transition().duration(1000)
                .remove();
    
    
            var sPoints = selection.select('.context').selectAll('.bar').data(data);
    
            var newsPoints = sPoints.enter().append('rect')
                .attr('class', 'bar')
                .attr('x', (d, i) => {
                    return scale.x2(i) - xBand.bandwidth() * 0.9 / 2
                })
                .attr('y', (d, i) => scale.y2(d.Prob))
                .attr('width', xBand.bandwidth() * 0.9)
                .attr('height', d => {
                    return height2 - scale.y2(d.Prob)
                });
    
            sPoints.merge(newsPoints)
                .transition().duration(1000)
                .attr('x', (d, i) => {
                    return scale.x2(i) - xBand.bandwidth() * 0.9 / 2
                })
                .attr('y', (d, i) => scale.y2(d.Prob))
                .attr('width', xBand.bandwidth() * 0.9)
                .attr('height', d => {
                    return height2 - scale.y2(d.Prob)
                });
    
            sPoints.exit()
                .transition().duration(1000)
                .remove();
    
    
    
        }
    
    
        function brushed() {
            var s = d3.event.selection || scale.x2.range()
            scale.x.domain(s.map(scale.x2.invert, scale.x2))
            focus.select('.axis').call(axis.x)
            focus.selectAll('.bar')
                .attr('x', (d, i) => {
                    return scale.x(i) - xBand.bandwidth() * 0.9 / 2
                })
        }
    
    
    }
    <!DOCTYPE html>
    <html lang='en'>
    <head>
    <meta charset='utf-8'>
        <style type="text/css">
            .bar { fill: steelblue; }
        </style>
    
    <script src='https://d3js.org/d3.v4.min.js' type='text/javascript'></script>
    
    
    </head>
    <body>
      <div class='chart span4' id='myPlot'>
        <svg width="700" height="500">
          <g class="focus">
            <g class="axis"></g>
            <g class="axis axis--y"></g>
          </g>
          <g class="context">
            <g class="axis2"></g>
            <g class="brush"></g>
          </g>
        </svg>
       </div>
    </body>
    </html>

    【讨论】:

    • 太棒了!非常感谢安德鲁。它就像一个魅力。我花了几个小时寻找这样做!事实上,我试图在输入-更新-退出模式的最开始添加剪辑路径属性,就在我们绑定数据之前。请问有没有办法在js代码之外和html内部定义clipPath的矩形?因此,js 中的代码只会抓取和操作它而不是附加它,因为它已经存在
    • 当然,在fiddle 中,我使用 HTML 在 DOM 中创建了剪辑路径,然后选择剪辑路径中的矩形并调整宽度/高度以匹配绘图区域的尺寸(如果你事先知道这些,你也可以在 HTML 中指定它们,完全不需要 d3 修改剪辑路径)。
    • 感谢您的帮助!那真的很棒。我尝试了一些非常接近这个的东西,我实际上是把 clipPath 和 rect 放在焦点组中,但由于某种原因我无法从 js 代码中获取它。我想要这个的原因是当用户单击散点图上的点时,这个条形图将被更新。条形图将显示与点击点相关的信息。如果clipPath 和其他元素是从js 中附加的,那么每次解析barchart js 脚本时(即每次鼠标点击)都会创建它们。现在只显示其中一个元素。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    • 2014-11-25
    • 1970-01-01
    • 2018-04-26
    相关资源
    最近更新 更多