如何使用Plotly.js绘制频率直方图?
Plotly.js提供API来绘制具有一组值但不包含频率值的直方图。
您可以在此处找到有关Plotly Histograms的更多信息 - https://plot.ly/javascript/histograms/
以下是一个例子:
如果样本集是{2,3,4,5,2,2,3,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 :(得分: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);
&#13;
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="myDiv"></div>
&#13;