gpt4 book ai didi

javascript - 计算数组的百分比

转载 作者:行者123 更新时间:2023-12-03 07:37:27 24 4
gpt4 key购买 nike

我正在尝试使用堆积条形图的百分比值填充 jqPlot 图表。我通过 mysql 和 COUNT 获取数据。例如,如果我有 4 个类别和 12 个月,我能够生产:

var s1 = [0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, ]; 
var s2 = [0, 5, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, ];
var s3 = [0, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, ];
var s4 = [0, 3, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, ];

这会生成一个带有数字的堆积条形图,每个变量的每个数字都是一个月份值。

现在我想显示一个堆积条形图,其中每个月的值都是百分比。我必须能够以某种方式使用数组的值进行百分比计算。例如:将位置二(二月)的所有值相加(100/(2+5+3+3)),然后与位置二相乘。

我还没有找到解决方案。

<小时/>

编辑:好的,感谢您的快速解答。

我会尽力解释得更好。我从“MySQL”查询中获取数据,然后将其转换为 PHP 数组,然后将其转换为字符串以将其粘贴到 JavaScript 中进行绘图:

Screenshot

最佳答案

尝试使用 for 循环来计算您想要获取的百分比并将其再次放入数组中

$(document).ready(function(){
var s1 = [0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, ];
var s2 = [0, 5, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, ];
var s3 = [0, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, ];
var s4 = [0, 3, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, ];
var s5 = new Array();
for (var i = 0; i < s1.length; i++){
//Or use your own formula on getting the value you wanted.
s5.push(100/(s1[i]+s2[i]+s3[i]+s4[i]);
}

// Can specify a custom tick Array.
// Ticks should match up one for each y value (category) in the series.
var ticks = ['January','February','March','April','May','June','July','August','September','October','November','December'];

var plot1 = $.jqplot('chart1', [s1, s2, s3, s4, s5], {
// The "seriesDefaults" option is an options object that will
// be applied to all series in the chart.
seriesDefaults:{
renderer:$.jqplot.BarRenderer,
rendererOptions: {fillToZero: true}
},
// Custom labels for the series are specified with the "label"
// option on the series option. Here a series option object
// is specified for each series.
series:[
{label:'Hotel'},
{label:'Event Regristration'},
{label:'Airfare'}
],
// Show the legend and put it outside the grid, but inside the
// plot container, shrinking the grid to accomodate the legend.
// A value of "outside" would not shrink the grid and allow
// the legend to overflow the container.
legend: {
show: true,
placement: 'outsideGrid'
},
axes: {
// Use a category axis on the x axis and use our custom ticks.
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: ticks
},
// Pad the y axis just a little so bars can get close to, but
// not touch, the grid boundaries. 1.2 is the default padding.
yaxis: {
pad: 1.05,
tickOptions: {formatString: '$%d'}
}
}
});
});

关于javascript - 计算数组的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35549118/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com