如何在D3的同一图上绘制多个矩形 [英] How do I plot multiple rectangles on the same plot in d3

查看:305
本文介绍了如何在D3的同一图上绘制多个矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用csv文件中的数据在单个图上创建多个矩形.使用我目前的方法,我似乎正在为每行数据创建多个图.我怀疑我的问题与我对数据的选择和附加svg元素有关.

I am trying to create multiple rectangles on a single plot using data from a csv file. With my current approach, I am appear to be creating multiple plots per each row of data. I suspect that my problem has something to do with how I select and append my svg element in regards to my data.

d3.csv('Input/test_single.csv')
  .row(function (d) { return d })
  .get(function (error, rows) {
    var chart = d3.select("#chart-div").data(rows).enter().append("svg").classed("chart", true).attr("width", width);

    chart.append("rect")
         .attr("x", function(d){return(parseInt(d.Start) + parseInt(spacer))})
         .attr("y", 75)
         .attr("width", function(d){return(parseInt(d.End) - parseInt(d.Start))}) 
         .attr("height", 50)
         .style("stroke", "rgb(255,0,0)")
         .style("stroke-width", 2)
});

推荐答案

阅读有关联接的思考,您正在做的是创建多个svg节点,而不是创建具有多个矩形的单个svg

Read thinking with joins, what you're doing is creating multiple svg nodes instead of a single svg with multiple rects

d3.csv('Input/test_single.csv')
  .row(function (d) { return d })
  .get(function (error, rows) {
    var chart = d3.select("#chart-div").append('svg').classed("chart", true).attr("width", width)

    chart.selectAll('rect').data(rows)
      .enter()
      .append("rect")
      .attr("x", function(d){return(parseInt(d.Start) + parseInt(spacer))})
      .attr("y", 75)
      .attr("width", function(d){return(parseInt(d.End) - parseInt(d.Start))}) 
      .attr("height", 50)
      .style("stroke", "rgb(255,0,0)")
      .style("stroke-width", 2)
});

这篇关于如何在D3的同一图上绘制多个矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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