gpt4 book ai didi

javascript - D3.js 折线图工具提示问题

转载 作者:行者123 更新时间:2023-11-29 16:53:17 26 4
gpt4 key购买 nike

我使用 d3.js 创建了一个折线图,并在图表中添加了工具提示,鼠标悬停时会创建一个小圆圈并显示 y 轴值。到这个阶段一切正常,但问题在于鼠标悬停时显示的圆圈的位置。

我希望这个圆显示在线上,但它总是显示在折线图上方或下方。

所以,我必须解决问题:

  1. 要修复 Tooltip 圆圈,使其始终位于折线图的线上?
  2. 如何显示定义点之间的点的 y 值?

我正在使用 .interpolate("basis") 来生成线,因为圆的位置被弄乱了。我不知道如何解决这个问题,因为我的代码中需要 .interpolate("basis")

请任何人知道如何解决此代码中的这些问题:

var data = [{
x: '1-May-12',
y: 5
}, {
x: '30-Apr-12',
y: 28
}, {
x: '27-Apr-12',
y: 58
}, {
x: '26-Apr-12',
y: 88
}, {
x: '25-Apr-12',
y: 8
}, {
x: '24-Apr-12',
y: 48
}, {
x: '23-Apr-12',
y: 28
}, {
x: '20-Apr-12',
y: 68
}, {
x: '19-Apr-12',
y: 8
}, {
x: '18-Apr-12',
y: 58
}, {
x: '17-Apr-12',
y: 5
}, {
x: '16-Apr-12',
y: 80
}, {
x: '13-Apr-12',
y: 38
}],
width = 1200,
height = 360,
margin = {
top: 30,
right: 20,
bottom: 30,
left: 50
};
width -= margin.left - margin.right;
height -= margin.top - margin.bottom;
var parseDate = d3.time.format("%d-%b-%y").parse;
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(0).tickSize(0)
.tickFormat("").outerTickSize(0);

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

var svg = d3.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.attr("class", "bg-color")
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

// function for the y grid lines
function make_y_axis() {
return d3.svg.axis()
.scale(y)
.orient("left")
.ticks(10);
}

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

x.domain(d3.extent(data, function(d) {
return parseDate(d.x);
}));
y.domain([0, d3.max(data, function(d) {
return d.y;
})]);

data.sort(function(a, b) {
return parseDate(a.x) - parseDate(b.x);
});

/*x.domain([parseDate(data[0].x), parseDate(data[data.length - 1].x)]);
y.domain(d3.extent(data, function (d) {
return d.y;
}));*/

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

// Add the Y Axis
svg.append("g")
.attr("class", "y axis")
.call(yAxis);

// Add the valueline path
svg.append("path")
.attr("class", "line");

// Define the line
var lineGen = d3.svg.line()
.x(function(d) {
return x(parseDate(d.x));
})
.y(function(d) {
return y(d.y);
})
.interpolate("basis");

svg.append('path')
.attr("class", "line")
.attr('d', lineGen(data));

var focus = svg.append("g")
.attr("class", "focus")
.style("display", "none");

focus.append("circle")
.attr("r", 4.5);

focus.append("text")
.attr("x", 9)
.attr("dy", ".35em");

svg.append("rect")
.attr("class", "overlay")
.attr("width", width)
.attr("height", height)
.on("mouseover", function() {
focus.style("display", null);
})
.on("mouseout", function() {
focus.style("display", "none");
})
.on("mousemove", mousemove);

var bisectDate = d3.bisector(function(d) {
return parseDate(d.x);
}).left;

function mousemove() {
var x0 = x.invert(d3.mouse(this)[0]),
i = bisectDate(data, x0, 1),
d0 = data[i - 1],
d1 = data[i],
d = x0 - parseDate(d0.x) > parseDate(d1.x) - x0 ? d1 : d0;
console.log(y(d.y));
focus.attr("transform", "translate(" + x(parseDate(d.x)) + "," + y(d.y) + ")");
focus.select("text").text(d.y);
}
.x.axis path {
display: none;
}

.line {
fill: none;
stroke: steelblue;
stroke-width: 1.5px;
}

.overlay {
fill: none;
pointer-events: all;
}

.focus circle {
fill: none;
stroke: steelblue;
}

.axis path,
.axis line {
fill: none;
stroke: grey;
stroke-width: 2;
shape-rendering: crispEdges;
}

.grid .tick {
stroke: lightgrey;
stroke-opacity: 0.7;
shape-rendering: crispEdges;
}

.grid path {
stroke-width: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

https://jsfiddle.net/nikunj2512/w5y1q5ds/1/

最佳答案

这个问题时常出现,我能想到两种解决方法。

解决方案 1——您可以解析路径本身并将这些点(和值)显示为您的工具提示以保持在合适的路径上。此解决方案的缺点是,根据 d3 进行拟合的方式,您最终会得到额外的点或稍微错位的点:

// get path
var p = svg.select('.line')
.attr("d");
// parse it by M coords, L coords and C coords
// build an array of points used in generating the path
var points = p.split(/(?=[LMC])/).map(function(d){
var fChar = d.slice(0, 1);
if (fChar === "M" || fChar === "L"){
return d.slice(1, d.length)
.split(",")
.map(function(p){ return +p; });
} else if (fChar === "C") {
var s = d.split(",");
return [+s[s.length - 2], +s[s.length - 1]];
}
});
// modify the bisect our array of points
var bisectDate = d3.bisector(function(d) {
return d[0];
}).left;
// modify the mousemove
function mousemove() {
var x0 = d3.mouse(this)[0],
i = bisectDate(points, x0, 1) - 1,
y0 = y.invert(points[i][1]);

//console.log(y(d.y));
focus.attr("transform", "translate(" + points[i][0] + "," + points[i][1] + ")");
focus.select("text").text(y0);
}

解决方案 2 -- 让您的工具提示完全跟随路径。这是一种使用一些内置 SVG 结构的非常简单的方法:

var path = svg.select('.line').node();
var totLength = path.getTotalLength();
function mousemove() {
var x0 = d3.mouse(this)[0],
per = width / x0;
point = path.getPointAtLength(totLength / per)
y0 = y.invert(point.y);

focus.attr("transform", "translate(" + point.x + "," + point.y + ")");
focus.select("text").text(y0);
}

解决方案 1 - 完整的工作代码:

<!DOCTYPE html>
<html>

<head>
<script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
<style>
.x.axis path {
display: none;
}

.line {
fill: none;
stroke: steelblue;
stroke-width: 1.5px;
}

.overlay {
fill: none;
pointer-events: all;
}

.focus circle {
fill: none;
stroke: steelblue;
}

.axis path,
.axis line {
fill: none;
stroke: grey;
stroke-width: 2;
shape-rendering: crispEdges;
}

.grid .tick {
stroke: lightgrey;
stroke-opacity: 0.7;
shape-rendering: crispEdges;
}

.grid path {
stroke-width: 0;
}
</style>
</head>

<body>
<script>
var data = [{
x: '1-May-12',
y: 5
}, {
x: '30-Apr-12',
y: 28
}, {
x: '27-Apr-12',
y: 58
}, {
x: '26-Apr-12',
y: 88
}, {
x: '25-Apr-12',
y: 8
}, {
x: '24-Apr-12',
y: 48
}, {
x: '23-Apr-12',
y: 28
}, {
x: '20-Apr-12',
y: 68
}, {
x: '19-Apr-12',
y: 8
}, {
x: '18-Apr-12',
y: 58
}, {
x: '17-Apr-12',
y: 5
}, {
x: '16-Apr-12',
y: 80
}, {
x: '13-Apr-12',
y: 38
}],
width = 1200,
height = 360,
margin = {
top: 30,
right: 20,
bottom: 30,
left: 50
};
width -= margin.left - margin.right;
height -= margin.top - margin.bottom;
var parseDate = d3.time.format("%d-%b-%y").parse;
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(0).tickSize(0)
.tickFormat("").outerTickSize(0);

var yAxis = d3.svg.axis().scale(y)
.orient("left").tickSize(-width, 0, 0);
//.ticks(0)
//.tickFormat("");

var svg = d3.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.attr("class", "bg-color")
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

// function for the y grid lines
function make_y_axis() {
return d3.svg.axis()
.scale(y)
.orient("left")
.ticks(10);
}

x.domain(d3.extent(data, function(d) {
return parseDate(d.x);
}));
y.domain([0, d3.max(data, function(d) {
return d.y;
})]);


console.log(y.domain())

data.sort(function(a, b) {
return parseDate(a.x) - parseDate(b.x);
});

/*x.domain([parseDate(data[0].x), parseDate(data[data.length - 1].x)]);
y.domain(d3.extent(data, function (d) {
return d.y;
}));*/

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

// Add the Y Axis
svg.append("g")
.attr("class", "y axis")
.call(yAxis);

// Define the line
var lineGen = d3.svg.line()
.x(function(d) {
return x(parseDate(d.x));
})
.y(function(d) {
return y(d.y);
})
.interpolate("basis");

svg.append('path')
.attr("class", "line")
.attr('d', lineGen(data));

var focus = svg.append("g")
.attr("class", "focus")
.style("display", "none");

focus.append("circle")
.attr("r", 4.5);

focus.append("text")
.attr("x", 9)
.attr("dy", ".35em");

svg.append("rect")
.attr("class", "overlay")
.attr("width", width)
.attr("height", height)
.on("mouseover", function() {
focus.style("display", null);
})
.on("mouseout", function() {
focus.style("display", "none");
})
.on("mousemove", mousemove);


var p = svg.select('.line')
.attr("d");
var points = p.split(/(?=[LMC])/).map(function(d){
var fChar = d.slice(0, 1);
if (fChar === "M" || fChar === "L"){
return d.slice(1, d.length)
.split(",")
.map(function(p){ return +p; });
} else if (fChar === "C") {
var s = d.split(",");
return [+s[s.length - 2], +s[s.length - 1]];
}
});
var bisectDate = d3.bisector(function(d) {
return d[0];
}).left;
function mousemove() {
var x0 = d3.mouse(this)[0],
i = bisectDate(points, x0, 1) - 1,
y0 = y.invert(points[i][1]);

//console.log(y(d.y));
focus.attr("transform", "translate(" + points[i][0] + "," + points[i][1] + ")");
focus.select("text").text(y0);
}
</script>
</body>

</html>


解决方案 2 - 完整的工作代码:

<!DOCTYPE html>
<html>

<head>
<script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
<style>
.x.axis path {
display: none;
}

.line {
fill: none;
stroke: steelblue;
stroke-width: 1.5px;
}

.overlay {
fill: none;
pointer-events: all;
}

.focus circle {
fill: none;
stroke: steelblue;
}

.axis path,
.axis line {
fill: none;
stroke: grey;
stroke-width: 2;
shape-rendering: crispEdges;
}

.grid .tick {
stroke: lightgrey;
stroke-opacity: 0.7;
shape-rendering: crispEdges;
}

.grid path {
stroke-width: 0;
}
</style>
</head>

<body>
<script>
var data = [{
x: '1-May-12',
y: 5
}, {
x: '30-Apr-12',
y: 28
}, {
x: '27-Apr-12',
y: 58
}, {
x: '26-Apr-12',
y: 88
}, {
x: '25-Apr-12',
y: 8
}, {
x: '24-Apr-12',
y: 48
}, {
x: '23-Apr-12',
y: 28
}, {
x: '20-Apr-12',
y: 68
}, {
x: '19-Apr-12',
y: 8
}, {
x: '18-Apr-12',
y: 58
}, {
x: '17-Apr-12',
y: 5
}, {
x: '16-Apr-12',
y: 80
}, {
x: '13-Apr-12',
y: 38
}],
width = 1200,
height = 360,
margin = {
top: 30,
right: 20,
bottom: 30,
left: 50
};
width -= margin.left - margin.right;
height -= margin.top - margin.bottom;
var parseDate = d3.time.format("%d-%b-%y").parse;
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(0).tickSize(0)
.tickFormat("").outerTickSize(0);

var yAxis = d3.svg.axis().scale(y)
.orient("left").tickSize(-width, 0, 0);
//.ticks(0)
//.tickFormat("");

var svg = d3.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.attr("class", "bg-color")
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

// function for the y grid lines
function make_y_axis() {
return d3.svg.axis()
.scale(y)
.orient("left")
.ticks(10);
}

x.domain(d3.extent(data, function(d) {
return parseDate(d.x);
}));
y.domain([0, d3.max(data, function(d) {
return d.y;
})]);


data.sort(function(a, b) {
return parseDate(a.x) - parseDate(b.x);
});

/*x.domain([parseDate(data[0].x), parseDate(data[data.length - 1].x)]);
y.domain(d3.extent(data, function (d) {
return d.y;
}));*/

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

// Add the Y Axis
svg.append("g")
.attr("class", "y axis")
.call(yAxis);

// Define the line
var lineGen = d3.svg.line()
.x(function(d) {
return x(parseDate(d.x));
})
.y(function(d) {
return y(d.y);
})
.interpolate("basis");

svg.append('path')
.attr("class", "line")
.attr('d', lineGen(data));

var focus = svg.append("g")
.attr("class", "focus")
.style("display", "none");

focus.append("circle")
.attr("r", 4.5);

focus.append("text")
.attr("x", 9)
.attr("dy", ".35em");

svg.append("rect")
.attr("class", "overlay")
.attr("width", width)
.attr("height", height)
.on("mouseover", function() {
focus.style("display", null);
})
.on("mouseout", function() {
focus.style("display", "none");
})
.on("mousemove", mousemove);


var path = svg.select('.line').node();
var totLength = path.getTotalLength();
function mousemove() {
var x0 = d3.mouse(this)[0],
per = width / x0;
point = path.getPointAtLength(totLength / per)
y0 = y.invert(point.y);

focus.attr("transform", "translate(" + point.x + "," + point.y + ")");
focus.select("text").text(y0);
}
</script>
</body>

</html>

关于javascript - D3.js 折线图工具提示问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34349551/

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