gpt4 book ai didi

charts - 如何将事件添加到由 d3.js 创建的饼图的各个部分(弧)?

转载 作者:行者123 更新时间:2023-12-02 00:11:42 27 4
gpt4 key购买 nike

This is a basic code to create a pie chart for protocol distribution. In my .csv file, I have two columns viz., protocol name and the percentage.I want to add events on individual arcs. For example, when i click only on the arc containing TCP stats, it should lead to another page. Please help how can i do this. I was able to add click event for the pie chart as whole.

   <!DOCTYPE html>
<meta charset="utf-8">
<style>

body {
font: 10px sans-serif;
}

.arc path {
stroke: #fff;
}

</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>

var width = 960,
height = 500,
radius = Math.min(width, height) / 2;

var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);

var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(0);

var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.count; });

var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

d3.csv("flow_count.csv", function(error, data) {

data.forEach(function(d) {
d.count = +d.count;
});

var g = svg.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc");

g.append("path")
.attr("d", arc)
.style("fill", function(d) { return color(d.data.proto); });

g.append("text")
.attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
.attr("dy", ".35em")
.style("text-anchor", "middle")
.text(function(d) { return d.data.proto; });
g.on( "click", function(d,i) {
window.location.href='index.html';
})

});

</script>

最佳答案

在 "svg.selectAll(".bar") 中,您可以添加点击行:

svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.letter); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.frequency); })
.attr("height", function(d) { return height - y(d.frequency); })
.on("click", function(d) {
// code you want executed on the click event
});

关于charts - 如何将事件添加到由 d3.js 创建的饼图的各个部分(弧)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14963208/

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