gpt4 book ai didi

javascript - 在 D3 中缩小时如何按时间尺度对图标进行聚类?

转载 作者:行者123 更新时间:2023-11-28 01:23:18 25 4
gpt4 key购买 nike

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

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

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

例如,如果 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>

最佳答案

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

它在解析期间为日期提供固定的 y 坐标。它计算日期的月份组。分组之后分组的key就是Time-in-milliseconds所以我们在使用的时候必须先把它转换成日期:new Date().setTime(parseInt(d.key))

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

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

每个缩放/平移 Action 都基于新的 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>

关于javascript - 在 D3 中缩小时如何按时间尺度对图标进行聚类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51370137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com