使用javascript创建基于字典长度的多个图表



我是javascript新手,尝试使用Canvasjs绘制javascript中字典长度的多个图形和。我有一个字典,其中包含从flask传递到模板的元组列表,这是我的字典。

{'923114566780479 (1).xlsx': [('181112949', 1), ('156860', 1), ('3007322293014', 3), ('3007789510214', 2)], 'Copy of 9231645678120167 (1).xlsx': [(383362396260316, 1), ('0310566103033882', 13), ('0315311456791689', 1), ('0315826247894310', 1)]}

在这个字典中,我有两个键,因为我上传了两个文件,我想要两个图表如果用户上传了5或6个,那么我想要5或6个图表。

这是我尝试过的代码

<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script>
{%for key in first%}
var myvar = '{{key}}';
console.log(myvar);
{%endfor%}
</script>
<script>
window.onload = function () {
{% for key in first %}
$('#piechart').append('<div id="draw_chart'+myvar+'"></div>');
chart = new CanvasJS.Chart(myvar, {
animationEnabled: true,
exportEnabled: false,
theme: "light1", // "light1", "light2", "dark1", "dark2"
backgroundColor: "transparent",
data: [{
type: "doughnut",
startAngle: 20,
//innerRadius: 10,
indexLabelFontSize: 17,
indexLabelFontColor: "black",
indexLabel: "#percent%",
toolTipContent: "<b>{label}:</b> {y}",
dataPoints: [
{%for b in first[key]%}
{ y: {{[b][0][1]}}, label: "{{[b][0][0]}}" },
{%endfor%}
]
}]
});
var container = document.getElementById('draw_chart'+myvar).appendChild(document.createElement('div'));
chart.render();
{%endfor%}
}
</script>
<body>
<div class="card-body">
<div class="row">
<div class="col-md-6">
<div class="card-body" id="piechart" style="min-height: 250px; height: 250px; max-height: 250px; max-width: 90%;">
</div>
</div>
</div>
</div>
</body>

任何帮助都将不胜感激。

Thanks In Advance.

用来创建图表的容器不合适。同样,myvar将指向字典中最后一个元素的键。所以,容器的id应该是id="draw_chart'+'{{key}}'+'",你应该在创建像new CanvasJS.Chart("draw_chart'+'{{key}}', {})这样的图表时传递相同的值。

请看下面的代码片段。

window.onload = function() {
var charts = []; { %
for key in first %
}
$('#piechart').append('<div id="draw_chart' + '{{key}}' + '" style="height: 300px;width: 100%;"></div>');
charts.push(new CanvasJS.Chart("draw_chart" + '{{key}}', {
animationEnabled: true,
exportEnabled: false,
theme: "light1", // "light1", "light2", "dark1", "dark2"
backgroundColor: "transparent",
data: [{
type: "doughnut",
startAngle: 20,
//innerRadius: 10,
indexLabelFontSize: 17,
indexLabelFontColor: "black",
indexLabel: "#percent%",
toolTipContent: "<b>{label}:</b> {y}",
dataPoints: [
{ %
for b in first[key] %
} {
y: {
{
[b][0][1]
}
},
label: "{{[b][0][0]}}"
},
{ % endfor %
}
]
}]
})); { % endfor %
}
charts.forEach(chart => chart.render())
}

相关内容

  • 没有找到相关文章

最新更新