score:8

*Accepted answer*

To add a line to your plot, all that you need to do is to append some line SVGs to your main SVG (`chart`

) or to the group that contains your SVG elements (`main`

).

Your code would look something like the following:

```
chart.append('line')
.attr('x1',x(10))
.attr('x2',x(20))
.attr('y1',y(5))
.attr('y2',y(10))
```

This would draw a line from (10,5) to (20,10). You could similarly create a data set for your lines and append a whole bunch of them.

One thing you might be interested in is the SVG path element. This is more common for lines than drawing one straight segment at a time. The documentation is here.

On another note you may find it easier to work with data in d3 if you create it all as one object. For example, if your data was in the following form:

```
data = [{x: 5, y:3}, {x: 10, y:17}, {x: 15, y:4}, {x: 20, y:6}]
```

You could use:

```
g.selectAll("scatter-dots")
.data(ydata) // using the values in the ydata array
.enter().append("svg:circle") // create a new circle for each value
.attr("cy", function (d) { return y(d.y); } ) //set y
.attr("cx", function (d,i) { return x(d.x); } ) //set x
```

This would eliminate potentially messy indexing if your data gets more complex.

score:3

UPDATE: Here is the relevant block: https://bl.ocks.org/HarryStevens/be559bed98d662f69e68fc8a7e0ad097

I wrote this function to calculate a linear regression from data, formatted as JSON.

It takes 5 parameters: 1) Your data 2) The column name of the data plotted on your x-axis 3) The column name of the data plotted on your y-axis 4) The minimum value of your x-axis 5) The minimum value of your y-axis

I got the formula for calculating a linear regression from http://classroom.synonym.com/calculate-trendline-2709.html

```
function calcLinear(data, x, y, minX, minY){
/////////
//SLOPE//
/////////
// Let n = the number of data points
var n = data.length;
var pts = [];
data.forEach(function(d,i){
var obj = {};
obj.x = d[x];
obj.y = d[y];
obj.mult = obj.x*obj.y;
pts.push(obj);
});
// Let a equal n times the summation of all x-values multiplied by their corresponding y-values
// Let b equal the sum of all x-values times the sum of all y-values
// Let c equal n times the sum of all squared x-values
// Let d equal the squared sum of all x-values
var sum = 0;
var xSum = 0;
var ySum = 0;
var sumSq = 0;
pts.forEach(function(pt){
sum = sum + pt.mult;
xSum = xSum + pt.x;
ySum = ySum + pt.y;
sumSq = sumSq + (pt.x * pt.x);
});
var a = sum * n;
var b = xSum * ySum;
var c = sumSq * n;
var d = xSum * xSum;
// Plug the values that you calculated for a, b, c, and d into the following equation to calculate the slope
// m = (a - b) / (c - d)
var m = (a - b) / (c - d);
/////////////
//INTERCEPT//
/////////////
// Let e equal the sum of all y-values
var e = ySum;
// Let f equal the slope times the sum of all x-values
var f = m * xSum;
// Plug the values you have calculated for e and f into the following equation for the y-intercept
// y-intercept = b = (e - f) / n = (14.5 - 10.5) / 3 = 1.3
var b = (e - f) / n;
// return an object of two points
// each point is an object with an x and y coordinate
return {
ptA : {
x: minX,
y: m * minX + b
},
ptB : {
y: minY,
x: (minY - b) / m
}
}
}
```

Source: stackoverflow.com

#### Related Query

- how do you draw linear line in scatter plot with d3.js
- How to draw a scatter plot with multiple y values for each x value?
- With nvd3.js/d3.js, how can you have a scatter or line chart with discrete/non-numeric/non-time-series X-Axis values?
- How to draw line with arrow using d3.js
- How to draw a *simple* line segment with d3.js?
- How to draw logarithmic line charts with nvd3
- How can I plot positive and negative values for both axes in a scatter plot with d3?
- How to draw line charts with complex data structures in d3
- How do you get JSON data and create a line chart with d3.js?
- How do you plot a line using scaleOrdinal in D3.js?
- How do you find the last data point in d3 and draw a circle and a line on it?
- d3.js How to draw line chart with vertical x axis labels
- How to handle the scales with d3.drag in a scatter plot
- How to draw a multi line series graph using d3.js with json data using angular directives
- How to render dates on x axis prior to 1900 with d3 .js scatter plot
- How to color the area under a scatter plot with different colors
- How to draw curved ( interpolated ) line point by point with D3?
- How do you create a d3 line function that will draw 2 lines for x, y1, y2 data?
- How to draw a vertical line with dimple?
- How to make a Scatter plot with D3 using a JSON file as input
- How not to display missing values in a multi line plot with D3js
- On common x-axis how to draw a chart with different unit of dataset array (multi line chart)
- how to draw a line between two axes with a data? (d3.js)
- D3js: how to plot multiseries line chart with json data
- nvd3 - how to draw a line over a scatterPlusLineChart, with specific cordinates
- How can I use d3.layout.stack with this code to draw a line chart using D3.js?
- How to draw straight line in d3.js (horizontally and vertically)
- How to draw a line / link between two points on a D3 map based on latitude / longitude?
- how do you set a fixed link distance with d3 v4
- How do we change the tick values generated by a linear scale in a d3.js line plot?

#### More Query from same tag

- React Native d3 azimuthal equal-area rotate not smooth
- Crossbrowser svg donut chart
- D3 library not converting value properly (React Native)
- C3 Chart shows negative y-Labels
- D3 click event redirect to Angular route
- n3-charts plot data with dates as the x-axis
- D3js collapsible tree entering transition using depth first style
- how to create co-ordinates in svg for d3 js map
- How to reset force directed graph to its original position?
- 3D Pie Chart using d3.js
- d3js multi-line scatterplot zoom
- Algorithm for automatic placement of flowchart shapes
- Displaying SVG elements with D3 and d3.slider: Uncaught TypeError: Cannot read property 'length' of undefined
- d3.js Throbbing marker points on a map
- D3 bar chart from objects with arrays
- filter out rows with 0s from dataTable when heatMap boxOnClick
- In D3.js, how to only add a comma on numbers with 5+ digits?
- dc.js Composite Graph - Plot New Line for Each Person
- Collision detection for nodes of varying sizes not working as expected
- Module '"../node_modules/@types/d3"' has no exported member 'event'
- how to move multiple paths to the left with a fluid animation between my data
- Draw arc with array data
- Datamaps not displaying in my browser
- d3.js Line chart tooltip content not showing
- github pages serve javascript / d3 visualizations
- How do I get the width of a bar including padding in d3?
- How can on make a static force graph in D3.js V4?
- Display text on rect using D3.js
- using d3.js, how can i select a particular <g> which has particular text in <text> as its child?
- get specific word on click event for SVG Text element