AndiAna
AndiAna

Reputation: 964

How to do a simple 2D contour plot using d3-contour?

Lets say i have a 4 x 5 array of numbers and i simply want to make a 2D contour plot in D3.

eg.

data = [[0.01, 0.012, 0.034, 0.024],[0.01, 0.012, 0.034, 0.024],[0.01, 0.012, 0.034, 0.024],[0.01, 0.012, 0.034, 0.024],[0.01, 0.012, 0.034, 0.024]];

and i want something looking like this?

enter image description here

I went through a lot of examples without success.

Can't even get the example here to work https://github.com/d3/d3-contour

Upvotes: 1

Views: 1133

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102198

Instead of your multidimensional array, you need to pass the data as a simple array:

const data = [0.01, 0.012, 0.034, 0.024, 0.01, 0.012, 0.034, 0.024, 0.01, 0.012, 0.034, 0.024, 0.01, 0.012, 0.034, 0.024, 0.01, 0.012, 0.034, 0.024];

Then, you define the width and height (in your case, 4 and 5) in the contour generator itself:

.size([4, 5])

Also, you'll need to set the adequate thresholds. Here's a simple demo with your 4x5 data:

const data = [0.01, 0.012, 0.034, 0.024, 0.01, 0.012, 0.034, 0.024, 0.01, 0.012, 0.034, 0.024, 0.01, 0.012, 0.034, 0.024, 0.01, 0.012, 0.034, 0.024];
const width = 4,
  height = 5,
  thresholds = 5;
const extent = d3.extent(data);
const contours = d3.contours()
  .size([width, height])
  .thresholds(d3.range(extent[0], extent[1], (extent[1] - extent[0]) / thresholds));
const contoursData = contours(data);
const projection = d3.geoIdentity()
  .fitSize([300, 150], contoursData[0]);
const path = d3.geoPath()
  .projection(projection);
const svg = d3.select("body").append("svg");
const paths = svg.selectAll(null)
  .data(contoursData)
  .enter()
  .append("path")
  .attr("d", path);
path {
  fill: wheat;
  stroke: black;
  stroke-width: 1;
}
<script src="https://d3js.org/d3.v7.min.js"></script>

Upvotes: 3

Related Questions