How to add a line graph to a scatter plot using d3?

I currently have a scatter plot that I use with this

var data = (an array of arrays with two integers in each array)

var margin = {top: 20, right: 15, bottom: 60, left: 60}
    , width = 300 - margin.left - margin.right
    , height = 250 - margin.top - margin.bottom;

var x = d3.scale.linear()
            .domain([0, d3.max(data, function(d) { return d[0]; })])
            .range([ 0, width ]);

var y = d3.scale.linear()
            .domain([0, d3.max(data, function(d) { return d[1]; })])
            .range([ height, 0 ]);

var chart = d3.select('.scatterGraph')
.append('svg:svg')
.attr('width', width + margin.right + margin.left)
.attr('height', height + margin.top + margin.bottom)
.attr('class', 'chart')


var main = chart.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
.attr('width', width)
.attr('height', height)
.attr('class', 'main')   

// draw the x axis
var xAxis = d3.svg.axis()
.scale(x)
.orient('bottom')
.ticks(5);

main.append('g')
.attr('transform', 'translate(0,' + height + ')')
.attr('class', 'main axis date')
.call(xAxis);

// draw the y axis
var yAxis = d3.svg.axis()
.scale(y)
.orient('left');

main.append('g')
.attr('transform', 'translate(0,0)')
.attr('class', 'main axis date')
.call(yAxis);

var g = main.append("svg:g"); 

g.selectAll("scatter-dots")
    .data(data)
    .enter().append("svg:circle")
        .attr("cx", function (d,i) { return x(d[0]); } )
        .attr("cy", function (d) { return y(d[1]); } )
        .attr("r", 2);

I was wondering how I could add a line graph (or, alternatively, another scatter plot) to this graph. I am very new to d3, so I'm currently getting lost on how to do this. For example, I just wanted to add the line described by the function y = 2t, where t is the x axis of the scatter plot. Thank!

+4
source share
1 answer

, , y=2t, line main , , width , height

main.append("line").attr("x1", 0).attr("x2", height/2)
                   .attr("y1", height).attr("y2", 0);

, , path svg d3.svg.line() d. - ,

var lineFunction = d3.svg.line().x(function (d) { x(d[0])}; )
                                .y(function (d) { y(d[1])}; );
var gLine = main.append("g");
gLine.append("path").attr("d", lineFunction(data));

var g = main.append("svg:g"); 

g.selectAll("scatter-dots")
.data(data2)
.enter().append("svg:circle")
    .attr("cx", function (d,i) { return x(d[0]); } )
    .attr("cy", function (d) { return y(d[1]); } )
    .attr("r", 2);

, .

+3

All Articles