## plotly.js

The open source JavaScript graphing library that powers Plotly

Show Sidebar Hide Sidebar

# 2D Histograms in plotly.js

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

#### 2D Histogram of a Bivariate Normal Distribution

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);


#### 2D Histogram Binning and Styling Options

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);


#### 2D Histogram Overlaid with a Scatter Chart

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);

Still need help?