Plotly.js - 绘制直方图的频率
问题描述:
如何使用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对此进行绘图?
答
检查这种表示方式。
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>
深思熟虑,但恐怕解决方案不能扩展。对于高于500的频率,该解决方案会对性能造成不利影响。在我的情况下,我有数量是10^4的订单。 –
@SGSVenkatesh没问题,只是给它一个镜头 –