2017-08-17 247 views
0

如何使用Plotly.js繪製頻率的直方圖?Plotly.js - 繪製直方圖的頻率

Plotly.js提供API來繪製直方圖的一組值,但不包含頻率值。

你可以找到更多關於Plotly直方圖這裏 - https://plot.ly/javascript/histograms/

下面是一個例子:

如果樣本集爲{2,3,4,5,2,2,2, 3,5}。 Plotly繪製這樣說 - 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); 

但是,這是我的數據有

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

這代表值0-2被重複4次,2-3被重複2次等上。

如何使用Plotly.js對此進行繪圖?

回答

0

檢查這種表示方式。

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>

+0

深思熟慮,但恐怕解決方案不能擴展。對於高於500的頻率,該解決方案會對性能造成不利影響。在我的情況下,我有數量是10^4的訂單。 –

+0

@SGSVenkatesh沒問題,只是給它一個鏡頭 –