简体   繁体   中英

Plotly.js - Plot histogram with frequency

How to draw a histogram with frequency using Plotly.js?

Plotly.js provides API to draw histogram with set of values but not with frequency values.

You can find more about Plotly Histograms here - https://plot.ly/javascript/histograms/

Here is an example:

If the sample set is { 2, 3, 4, 5, 2, 2, 2, 3, 5 }. Plotly plots it this way - https://codepen.io/sgsvenkatesh/pen/eEyyMJ

var x = [2, 3, 4, 5, 2, 2, 2, 3, 5];

var trace = {
    x: x,
    type: 'histogram',
  };
var data = [trace];
Plotly.newPlot('myDiv', data);

But this is the data I have

x = [2, 3, 4, 5];
y = [4, 2, 1, 1];

This represents that values 0-2 are repeated 4 times, 2-3 is repeated 2 times and so on.

How can I plot this using Plotly.js?

Check this mode of representation.

 x = [2, 3, 4, 5]; y = [4, 2, 1, 1]; traces = []; for (var i = 0; i <= x.length - 1; i++) { var yarray = new Array(y[i]).fill(y[i]); var trace = {}; if (i === 0) { trace = { x: yarray, type: 'histogram', name: 0 + " to " + x[i] }; } else if (i === x.length - 1) { trace = { x: yarray, type: 'histogram', name: x[i] + " and above" }; } else { trace = { x: yarray, type: 'histogram', name: x[i - 1] + " to " + x[i] }; } traces.push(trace); } var data = traces; var layout = {barmode: "group"}; // there are three modes that can be set, "overlay", "stack", "group" Plotly.newPlot('myDiv', data, layout); 
  <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> <div id="myDiv"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM