gpt4 book ai didi

javascript - 在 d3.js 中添加图像

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

我是 java 脚本和 d3.js 的新手。我想将图像添加到图表中的相应点。我浏览了很多问题和文章,但我无法正确地弄清楚这一点。以下是我的代码

<!DOCTYPE html>
<meta charset="utf-8">
<style>
.bar {
fill: steelblue;
}
.bar:hover {
fill: brown;
}
.axis--x path {
display: none;
}
.line {
fill: none;
stroke: steelblue;
stroke-width: 3px;
}
.circle {
fill: steelblue;
}
.axis--y path, .axis--y line {
fill: none;
stroke: none;
}
</style>
<svg width="960" height="500"></svg>
<script src="http://localhost/d3.js"></script>
<script>
var svg = d3.select("svg"),
margin = {top: 50, right: 50, bottom: 30, left: 80},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom;

var x= d3.scaleLinear().rangeRound([0, width]);

y = d3.scaleBand().range([height, 0]).padding(0.1);
var g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.tsv("http://localhost/data1.tsv", function(d) {
d.frequency = +d.frequency;
return d;
}, function(error, data) {
if (error) throw error;

var line = d3.line()
.x(function(d) { return x(d.frequency); })
.y(function(d) { return y(d.letter)+30; })
.curve(d3.curveStepAfter);

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

y.domain(data.map(function(d) { return d.letter; }));

g.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));

g.append("g")
.attr("class", "axis axis--y")
.call(d3.axisLeft(y))
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "0.71em")
.attr("text-anchor", "end")
.text("letter");

g.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);

});
</script>

该图像是上述代码的输出:

This image is the output of the above code

我想在行中添加图标或小图像,如下面的链接所示

此图片显示了我如何向图表添加图标:

This image shows how I want to add icons to my chart

与我类似的问题是How do I display an icon at a point on a line chart using d3.js ,但这对我不起作用,我也想添加我的自定义图标。

最佳答案

如果您想为工具提示添加图像,如下所示 example ,通过添加类似内容来用图像替换圆圈

focus.append('svg:image')
.attr({
'xlink:href': 'test.png',
x: 0,
y: 0,
width: 10,
height: 10
});

如果希望添加图像作为数据点,请查看此 example如上面的代码所示,用图像替换点。

关于javascript - 在 d3.js 中添加图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46937042/

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