如何将事件添加到由d3.js创建的饼图的各个部分(弧)中? [英] How to add events to the individual sections(arcs) of a pie chart created out of d3.js?

查看:80
本文介绍了如何将事件添加到由d3.js创建的饼图的各个部分(弧)中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是创建用于协议分发的饼图的基本代码.在我的.csv文件中,我有两列,即协议名称和百分比.我想在单个弧上添加事件.例如,当我仅单击包含TCP统计信息的弧时,它应指向另一页.请帮助我该怎么做.我能够为整个饼图添加click事件.

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")中,您可以添加一个单击行:

Within the "svg.selectAll(".bar") you could add an on click line:

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 
      });

这篇关于如何将事件添加到由d3.js创建的饼图的各个部分(弧)中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆