Show Sidebar Hide Sidebar

2D Histograms in MATLAB

How to make a 2D histogram in MATLAB. A 2D histogram is a visualization of a bivariate distribution.

% Learn about API authentication here: https://plot.ly/matlab/getting-started
% Find your api_key here: https://plot.ly/settings/api

x = randn(500,1);
y = randn(500,1)+1;

data = {...
  struct(...
    'x', x, ...
    'y', y, ...
    'type', 'histogram2d')...
};
response = plotly(data, struct('filename', '2d-histogram', 'fileopt', 'overwrite'));
plot_url = response.url
% Learn about API authentication here: https://plot.ly/matlab/getting-started
% Find your api_key here: https://plot.ly/settings/api

x = randn(500,1);
y = randn(500,1)+1;

data = {...
  struct(...
    'x', x, ...
    'y', y, ...
    'histnorm', 'probability', ...
    'autobinx', false, ...
    'xbins', struct(...
      'start', -3, ...
      'end', 3, ...
      'size', 0.1), ...
    'autobiny', false, ...
    'ybins', struct(...
      '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')...
};
response = plotly(data, struct('filename', '2d-histogram-options', 'fileopt', 'overwrite'));
plot_url = response.url
% Learn about API authentication here: https://plot.ly/matlab/getting-started
% Find your api_key here: https://plot.ly/settings/api

x0 = randn(100,1)./5. + 0.5;
y0 = randn(100,1)./5. + 0.5;
x1 = rand(50,1);
y1 = rand(50,1) + 1.0;

x = [x0; x1];
y = [y0; y1];

trace1 = struct(...
  'x', x0, ...
  'y', y0, ...
  'mode', 'markers', ...
  'marker', struct(...
    'symbol', 'circle', ...
    'opacity', 0.7), ...
  'type', 'scatter');
trace2 = struct(...
  'x', x1, ...
  'y', y1, ...
  'mode', 'markers', ...
  'marker', struct(...
    'symbol', 'square', ...
    'opacity', 0.7), ...
  'type', 'scatter');
trace3 = struct(...
  'x', x, ...
  'y', y, ...
  'type', 'histogram2d');
data = {trace1, trace2, trace3};
response = plotly(data, struct('filename', '2d-histogram-scatter', 'fileopt', 'overwrite'));
plot_url = response.url
Still need help?
Contact Us

For guaranteed 24 hour response turnarounds, upgrade to a Developer Support Plan.