Black Lives Matter. Please consider donating to Black Girls Code today.

2D Histograms in JavaScript

How to make a D3.js-based 2D histogram in javascript. A 2D histogram is a visualization of a bivariate distribution.


New to Plotly?

Plotly is a free and open-source graphing library for JavaScript. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

var x = [];
var y = [];
for (var i = 0; i < 500; i ++) {
	x[i] = Math.random();
	y[i] = Math.random() + 1;
}

var data = [
  {
    x: x,
    y: y,
    type: 'histogram2d'
  }
];
Plotly.newPlot('myDiv', data);
var x = [];
var y = [];
for (var i = 0; i < 500; i ++) {
	x[i] = Math.random();
	y[i] = Math.random() + 1;
}

var data = [
  {
    x: x,
    y: y,
    histnorm: 'probability',
    autobinx: false,
    xbins: {
      start: -3,
      end: 3,
      size: 0.1
    },
    autobiny: false,
    ybins: {
      start: -2.5,
      end: 4,
      size: 0.1
    },
    colorscale: [['0', 'rgb(12,51,131)'], ['0.25', 'rgb(10,136,186)'], ['0.5', 'rgb(242,211,56)'], ['0.75', 'rgb(242,143,56)'], ['1', 'rgb(217,30,30)']],
    type: 'histogram2d'
  }
];
Plotly.newPlot('myDiv', data);
var x0 = [];
var y0 = [];
var x1 = [];
var y1 = [];
var x2 = [];
var y2 = [];

for (var i = 0; i < 500; i ++)
{
	x0[i] = Math.random() + 1;
	y0[i] = Math.random() + 1.5;
}

for (var i = 0; i < 100; i ++)
{
	x1[i] = Math.random();
	y1[i] = Math.random() + 1;
}

for (var i = 0; i < 500; i ++)
{
	x2[i] = Math.random()*2;
	y2[i] = Math.random()*3;
}

var trace1 = {
  x: x0,
  y: y0,
  mode: 'markers',
  marker: {
    symbol: 'circle',
    opacity: 0.7,
	 color:'rgb(200,111,200)',
  },
  type: 'scatter',
};
var trace2 = {
  x: x1,
  y: y1,
  mode: 'markers',
  marker: {
    symbol: 'square',
    opacity: 0.7,
	 color:'cyan',
  },
  type: 'scatter'
};
var trace3 = {
  x: x2,
  y: y2,
  type: 'histogram2d',
  colorscale : [['0' , 'rgb(0,225,100)'],['1', 'rgb(100,0,200)']],
  
};

var data = [trace1, trace2, trace3];
Plotly.newPlot('myDiv', data);