【问题标题】:How to cluster icons in a time scale upon zooming out in D3?如何在 D3 中缩小时按时间尺度对图标进行聚类?
【发布时间】:2018-07-16 21:08:41
【问题描述】:

我有一个 D3(使用 D3 版本 3.5.2)时间刻度图表,此时仅使用 x 轴。该图基于日期数组在 x 轴上绘制一系列 svg“rect”元素,同时随机化 y 轴上的数据点以防止出现聚类问题。该图表还具有缩放和平移功能。

我想做的是在缩小比例时如下:

将所有图标聚集在一起,以便在用户缩小时根据时间线图表的特定垂直切片的“事件或数据点的集体重叠量”在缩小时显示一个新图标。

例如,如果有 7 个数据点聚集在 2018 年 5 月,那么它会显示一个图标,其中包含该特定垂直时间片(或 2018 年 5 月)的事件数,显示在图标,因此在这种情况下,数字 7 将出现在群集图标框中。放大到 2018 年 5 月会导致“聚集图标”消失,并显示实际显示的七个单独的“矩形”元素(例如周二、23 日、周四、25 日等...)。

这里的棘手部分是获取特定日期的缩小垂直切片的实际元素数量,并在用户缩小时呈现集群图标,并在用户放大时执行相反的操作(隐藏集群图标并在时间轴上呈现单个图标)。

这是我当前的代码:

//D3 Timescale demo

const width = 1200,
    height = 500,
    parsedDate = d3.time.format('%Y-%m-%d').parse;

const changedDates = [
    '1988-01-01', '1988-01-02', '1988-01-03',
    '1988-01-04', '1988-01-05', '1988-01-06',
    '1988-01-07', '1989-01-08', '1989-01-09',
    '1995-01-10', '1995-01-11', '1998-01-12',
    '1998-01-13', '1998-01-14', '2002-01-15',
    '2002-01-16', '2002-01-17', '2004-01-18',
    '2004-01-19', '2004-01-20', '2004-01-21',
    '2004-01-22', '2007-01-23', '2007-01-24',
    '2007-01-25', '2007-01-26', '2007-01-27',
    '2008-01-28', '2008-01-29', '2008-01-30',
    '2008-01-31', '2008-02-01', '2010-02-02',
    '2010-02-03', '2010-02-04', '2012-02-05',
    '2012-02-06', '2012-02-07', '2012-02-08',
    '2014-02-09', '2014-02-10', '2014-02-11',
    '2017-02-12', '2017-02-13', '2017-02-14',
    '2018-02-15', '2018-02-16', '2018-02-17',
    '2018-02-18', '2018-02-19', '2018-02-20'
].map(d => parsedDate(d));

const svg = d3.select('#timescale')
        .append('svg')
            .attr('preserveAspectRatio', 'xMinYMin meet')
            .attr('viewBox', `0 0 ${width} ${height}`)
            .classed('svg-content', true);
        // .attr('width', width)
        // .attr('height', height);

const clipPath = svg.append('defs')
    .append('clipPath')
    .attr('id', 'clip')
    .append('rect')
    .attr('width', width - 110)
    .attr('height', height);

const xScale = d3.time.scale()
    .domain([new Date(Date.parse(d3.min(changedDates, d => d))), new Date(Date.parse(d3.max(changedDates, d => d)))])
    .range([10, width - 110]);

const yScale = d3.scale.linear()
    .domain([200, 0])
    .range([0, height - 29]);

const xAxis = d3.svg.axis()
    .scale(xScale)
    .tickSize(1)
    .orient('bottom');

const yAxis = d3.svg.axis()
    .scale(yScale)
    .tickSize(1)
    .tickValues([0, 100, 200])
    .orient('right');

const zoom = d3.behavior.zoom()
    .on('zoom', function () {
        svg.select('g.xaxis').call(xAxis).selectAll('text').style('font-size', '10px');
        updateEvents();
    }).x(xScale);

// Draw base area to interact on
const rect = svg.append('rect')
                .attr('x', 0)
                .attr('y', 0)
                .attr('width', width - 100)
                .attr('height', height)
                .attr('opacity', 0)
                .call(zoom);

svg.append('g')
    .attr('class', 'xaxis')
    .attr('transform', 'translate(' + 10 + ',' + 480 + ')')
    .call(xAxis)
    .selectAll('text')
    .style('font-size', '10px');

svg.append('g')
    .attr('class', 'yaxis')
    .attr('transform', 'translate(' + 1100 + ',' + 10 + ')')
    .call(yAxis)
    .selectAll('text')
    .style('font-size', '10px');

const renderEvents = dates => {
    const events = svg.selectAll('rect').data(dates);

    events.enter()
        .append('rect')
        .attr('class', 'item')
        .attr('x', d => xScale(d))
        .attr('y', () => Math.random() * 100)
        .attr('width', 10)
        .attr('height', 10)
        .attr('transform', (d, i)  => (i === changedDates.length - 1) ? 'translate(' + 0 + ',' + 362 + ')' : 'translate(' + 10 + ',' + 362 + ')')
        .attr('clip-path', 'url(#clip)')
        .style('fill', 'blue');

    events.exit()
        .remove();
}

const updateEvents = () =>  {
    // The console logs here are to try and figure the distinct amount of inverted x-scale values to try and decipher a pattern for the number of elements
    // needed to display in the clustered icon box.
    svg.selectAll('rect.item').attr('x', d => xScale(d)).classed('deleteIcon', d => { console.log('text d: ', Math.floor(xScale(d))); });
    console.log(`Elements on chart: ${svg.selectAll('rect.item').size()}`);
}

renderEvents(changedDates);
.svg-container {
    display: inline-block;
    position: relative;
    width: 100%;
    padding-bottom: 100%;
    vertical-align: top;
    overflow: hidden;
    top: 20px;
}

.svg-content {
    display: inline-block;
    position: absolute;
    top: 0;
    left: 0;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>D3 Timescale Intro</title>
    <link rel="stylesheet" href="./styles.css">
</head>

<body>
    <div id="timescale" class="svg-container"></div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.2/d3.min.js"></script>
    <script src="./timescale.js"></script>
</body>

</html>

【问题讨论】:

    标签: javascript html css d3.js cluster-analysis


    【解决方案1】:

    我已经实现了一个基于Pan & Zoom Axes的D3v5

    它在解析过程中给日期一个固定的 y 坐标。 它计算日期的月份组。分组后,组的键是毫秒时间,所以我们必须先将其转换为使用时的日期:new Date().setTime(parseInt(d.key))

    根据 X 轴上月份的分隔,它决定绘制单个点(蓝色)或组点(红色)。

    您必须调整文本的样式及其对齐方式。并且组点由于某种原因没有被剪裁。

    每个缩放/平移动作都基于新的xScale 重新绘制。

    <!DOCTYPE html>
    <meta charset="utf-8">
    <style>
    
    .axis path {
      display: none;
    }
    
    .axis line {
      stroke-opacity: 0.3;
      shape-rendering: crispEdges;
    }
    
    .view {
      fill: none;
      stroke:none;
    }
    
    button {
      position: absolute;
      top: 20px;
      left: 20px;
    }
    
    </style>
    <button>Reset</button>
    <div id="timescale" class="svg-container"></div>
    <script src="https://d3js.org/d3.v5.min.js"></script>
    <script>
    
    //D3 Timescale demo
    
    const width = 1200,
        height = 500,
        parsedDate = d3.utcParse("%Y-%m-%d");
    
    const changedDates = [
        '1988-01-01', '1988-01-02', '1988-01-03',
        '1988-01-04', '1988-01-05', '1988-01-06',
        '1988-01-07', '1989-01-08', '1989-01-09',
        '1995-01-10', '1995-01-11', '1998-01-12',
        '1998-01-13', '1998-01-14', '2002-01-15',
        '2002-01-16', '2002-01-17', '2004-01-18',
        '2004-01-19', '2004-01-20', '2004-01-21',
        '2004-01-22', '2007-01-23', '2007-01-24',
        '2007-01-25', '2007-01-26', '2007-01-27',
        '2008-01-28', '2008-01-29', '2008-01-30',
        '2008-01-31', '2008-02-01', '2010-02-02',
        '2010-02-03', '2010-02-04', '2012-02-05',
        '2012-02-06', '2012-02-07', '2012-02-08',
        '2014-02-09', '2014-02-10', '2014-02-11',
        '2017-02-12', '2017-02-13', '2017-02-14',
        '2018-02-15', '2018-02-16', '2018-02-17',
        '2018-02-18', '2018-02-19', '2018-02-20'
    ].map(d => { return { date: parsedDate(d), y: Math.random() * 100 + 50 }; });
    
    const svg = d3.select('#timescale')
            .append('svg')
                .attr('preserveAspectRatio', 'xMinYMin meet')
                .attr('viewBox', `0 0 ${width} ${height}`)
                .classed('svg-content', true);
            // .attr('width', width)
            // .attr('height', height);
    
    const clipPath = svg.append('defs')
        .append('clipPath')
        .attr('id', 'clip')
        .append('rect')
        .attr('width', width - 110)
        .attr('height', height);
    
    var minDate = d3.min(changedDates, d => d.date);
    var maxDate = d3.max(changedDates, d => d.date);
    minDate.setUTCFullYear(minDate.getUTCFullYear()-1);
    maxDate.setUTCFullYear(maxDate.getUTCFullYear()+1);
    
    const xScale = d3.scaleTime()
        .domain([minDate, maxDate])
        .range([10, width - 110]);
    
    const yScale = d3.scaleLinear()
        .domain([200, 0])
        .range([0, height - 29]);
    
    const xAxis = d3.axisBottom()
        .scale(xScale)
        .tickSize(1);
    
    const yAxis = d3.axisRight()
        .scale(yScale)
        .tickSize(1)
        .tickValues([0, 100, 200]);
    
    var view = svg.append("rect")
        .attr("class", "view")
        .attr("x", 0.5)
        .attr("y", 0.5)
        .attr("width", width - 109)
        .attr("height", height - 28);
    
    var gX = svg.append('g')
        .attr('class', 'xaxis')
        .attr('transform', `translate(10,${height-20})`)
        .call(xAxis);
        // .selectAll('text')
        // .style('font-size', '10px');
    
    svg.append('g')
        .attr('class', 'yaxis')
        .attr('transform', 'translate(' + 1100 + ',' + 10 + ')')
        .call(yAxis);
        // .selectAll('text')
        // .style('font-size', '10px');
    
    var zoom = d3.zoom()
        .scaleExtent([1, 100])
    //    .translateExtent([[-100, -100], [width + 90, height + 100]])
        .on("zoom", zoomed);
    
    d3.select("button")
        .on("click", resetted);
    
    svg.call(zoom);
    
    var points = svg.append("g")
        .attr('class', 'points');
    
    var monthCount = d3.nest()
        .key(function(d) { return Date.UTC(d.date.getUTCFullYear(), d.date.getUTCMonth(), 1); })
        .rollup(function(v) { return { count: v.length, y: Math.random() * 100 + 50 }; })
        .entries(changedDates);
    
    function drawDates(dates, xScale) {
      var points = svg.select(".points");
      points.selectAll(".item").remove();
      // use domain to group the dates
      var minDate = xScale.domain()[0];
      var minDatep1m = new Date(minDate.getTime()+30*24*60*60*1000); // + 1 month
      var deltaX = xScale(minDatep1m) - xScale(minDate);
      if (deltaX > 20) {
        points.selectAll('.item')
          .data(dates)
          .enter()
          .append('rect')
          .attr('class', 'item')
          .attr('x', d => xScale(d.date))
          .attr('y', d => d.y)
          .attr('width', 10)
          .attr('height', 10)
          .attr('clip-path', 'url(#clip)')
          .style('fill', 'blue');
      } else {
        var groups = points.selectAll('.item')
          .data(monthCount)
          .enter()
          .append('g')
          .attr('class', 'item')
          .attr('transform', d => `translate(${xScale(new Date().setTime(parseInt(d.key)))},${d.value.y})`);
        groups.append('rect')
          .attr('x', -5)
          .attr('y', -5)
          .attr('width', 10)
          .attr('height', 10)
          .attr('clip-path', 'url(#clip)')
          .style('fill', 'red');
        groups.append('text')
          .text(d => d.value.count);
      }
    }
    
    drawDates(changedDates, xScale);
    
    function zoomed() {
      var transformedX = d3.event.transform.rescaleX(xScale);
      gX.call(xAxis.scale(transformedX));
      drawDates(changedDates, transformedX)
    }
    
    function resetted() {
      svg.transition()
          .duration(750)
          .call(zoom.transform, d3.zoomIdentity);
    }
    
    </script>
    

    【讨论】:

    • 非常感谢您的帮助,但是我面临的一些挑战是尝试从您的代码中找到与我使用 d3 v3.5 库的代码的等效项。例如,您正在使用以下方法设置缩放比例: function zoomed() { var transformX = d3.event.transform.rescaleX(xScale); gX.call(xAxis.scale(transformedX)); drawDates(changedDates, encryptedX) } 我如何将其转换为使用 d3 v3.5,例如,我试图找到与 transform.rescaleX 等效的 d3 v3.5?
    • 逻辑是正确的,我正在尝试使用 d3 v3.5 实现一个版本。您能否发送一个使用版本 3.5 的示例,因为版本 5 中发生了很多变化,但由于其他图表的向后兼容性原因,我无法升级。再次非常感谢。
    • 搜索使用 d3v3 的缩放示例。并查看绘制新轴的代码。将 v3 代码移植到 v5 只需几分钟,并且所有 v3 都可以在 v5 中完成,因此没有理由坚持使用 v3。除了 colorCategory20,您可以在 v4 中找到等价物并将这些颜色数组复制到您的代码中。我不编写 v3 代码,我将所有需要的内容移植到 v5。
    • 谢谢,我在正确的轨道上,但是我需要在我的更新函数中使用相同的 xScale 调用我的渲染方法,因为 D3 v3.5 没有重新缩放功能。现在正在运行,再次感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2013-07-21
    • 1970-01-01
    • 2019-09-01
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-18
    • 2010-10-13
    相关资源
    最近更新 更多