https://medium.com/@kj_schmidt/making-a-simple-scatter-plot-with-d3js-58cc894d7c97

 

Making a simple scatter plot with d3.js
KJ Schmidt
Feb 20, 2019 · 3 min read
 
Making a simple scatter plot with d3.js
Making a simple scatter plot with d3.js

Getting started

This tutorial uses d3 v4.6. The CDN is hosted on Cloudflare, so you can start by adding this script tag to your html file:

#scatter in this tutorial) where you’d like the scatter plot to go:

(don’t forget to go back to your html file and add a script tag for it!).

United States Department of Labor:

data = [{
date: 2009,
wage: 7.25
}, {
date: 2008,
wage: 6.55
}, {
date: 2007,
wage: 5.85
}, {
date: 1997,
wage: 5.15
}, {
date: 1996,
wage: 4.75
}, {
date: 1991,
wage: 4.25
}, {
date: 1981,
wage: 3.35
}, {
date: 1980,
wage: 3.10
}, {
date: 1979,
wage: 2.90
}, {
date: 1978,
wage: 2.65
}]

Get going on the graph

First, we’ll set our variables for margin, width, and height.

width = 700 - margin.left - margin.right;
height = 500 - margin.top - margin.bottom;

d3.timeParse() because my data includes dates. You can also sort your data, which I did from lowest to highest year. Sorting is only important here if you plan to connect your data points.

//sort the data by date
data.sort(function (a, b) {
return a.date - b.date;
});

.scaleLinear() for the y axis since it’s a continuous scale.

y.domain([0, d3.max(data, function (d) {
return d.wage;
})]);

d3.line(), which allows us to make either a scatter plot or a line chart.

var valueline = d3.line()
.x(function (d) {
return x(d.date);
})
.y(function (d) {
return y(d.wage);
});

#scatter div we made earlier in the html.

Optional: If you want to connect your data points like this, add this code for a trend line:

Making a simple scatter plot with d3.js
Making a simple scatter plot with d3.js

*make sure you sorted your data in the format/sort step, or you may have a weird shape here.

Almost done

It’s time to add the actual data points:

.attr lines.

.ticks().

     }));
Making a simple scatter plot with d3.js
Making a simple scatter plot with d3.js

You have a graph!

live.

tutorial for that!

相关文章:

  • 2021-04-25
  • 2022-01-25
  • 2021-08-21
  • 2021-06-05
  • 2021-12-02
  • 2022-12-23
猜你喜欢
  • 2021-08-01
  • 2021-05-29
  • 2021-09-04
  • 2021-05-25
  • 2021-11-16
相关资源
相似解决方案