Published
Edited
Sep 16, 2019
Importers
4 stars
Scatter Plot Plus Linear Regression
Also listed in…
Testing
Insert cell
Insert cell
chart = {
const svg = d3.select(DOM.svg(width, height));
svg.append("g").call(xAxis)
svg.append("g").call(yAxis)

svg.append("g")
.call(setTitle, "Scatter Chart is Good")
const dots = svg.append("g")
.call(addCircles, groceries.slice(0,15), mint, 5)
const dots2 = svg.append("g")
.call(addCircles, groceries.slice(16,50), "orange", 5)
svg.append("path")
.call(addLine, groceries, mint, 3)
return svg.node()
}
Insert cell
Insert cell
Insert cell
Insert cell
fittedLine = d3.line()
.x(d => x(d.x))
.y(d => y(d.y))
Insert cell
x = d3.scaleLinear()
.domain([d3.min(groceries, d=>parseFloat(d.Grocery)),d3.max(groceries, d=>parseFloat(d.Grocery))])
.range([30, width-30])
Insert cell
y = d3.scaleLinear()
.domain([d3.min(groceries, d=>parseFloat(d.Health)),d3.max(groceries, d=>parseFloat(d.Health))])
.range([height-30, 30])
Insert cell
xAxis = svg => svg
.attr("transform", `translate(0,${height - 30})`)
.call(d3.axisBottom(x))
Insert cell
yAxis = svg => svg
.attr("transform", `translate(${30},0)`)
.call(d3.axisLeft(y))
Insert cell
md`# Appendix`
Insert cell
Insert cell
Insert cell
tooltip = d3.select("body").append("div").attr("class", "toolTip");
Insert cell
groceries = Object.assign(await d3.csv("https://gist.githubusercontent.com/muvic08/e532c9644e219a2b35bfdd5818aa80ad/raw/80efedc6f19299212cad72669259bc32cc79f4fd/groceries.csv"))
Insert cell
regressionPoints2 = [
{x: 106, y: 91},
{x: 71, y: 114}
]
Insert cell
regressionPoints3 = [
{
x: x.domain()[1],
y: y.domain()[1]
},
{
x: x.domain()[0],
y: y.domain()[0]
}
]
Insert cell
regressionPoints = {
const firstX = d3.min(groceries.map(d => parseFloat(d.Grocery)));
const lastX = d3.max(groceries.map(d => parseFloat(d.Grocery)));
const xCoordinates = [firstX, lastX];
return xCoordinates.map(d => ({
x: d,
y: linearRegressionLine(d)
}));
}
Insert cell
linearRegressionLine2 = function(x) {
return params.M*x + params.C
}
Insert cell
linearRegressionLine = ss.linearRegressionLine(linearRegression)
Insert cell
linearRegression = ss.linearRegression(
groceries.map(d => [parseFloat(d.Grocery), parseFloat(d.Health)]))
Insert cell
params = ({M:1.2, C: 100})
Insert cell
d3 = require("d3@5")
Insert cell
ss = require('simple-statistics')
Insert cell
Insert cell
x.domain()
Insert cell
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more