0๐
โ
I didnโt find a way to pass "dictCategory" dictionary to chart.js. so I converted it to two list:
category_list = ['Business Analytics', 'Data ethics',
'visualization', 'statistics', 'NLP',
'Language', 'python', 'maths', 'deep
learning', 'SQL', 'Python', 'R
Studio', 'data science']
count_list = [336, 389, 314, 428, 368, 1, 373, 379, 364, 403,
80, 246, 395]
Then I use them in chart.js:
<script>
// jquery function
$(document).ready(function(){
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: [{% for data in category_list %} '{{data}}', {% endfor %}],
datasets: [{
label: '# of categories',
data: [{% for data in count_list %}{{data}},{% endfor %}],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)',
'rgba(54, 162, 64, 0.2)',
'rgba(255, 148, 64, 0.2)',
'rgba(75, 175, 192, 0.2)',
'rgba(255, 130, 64, 0.2)',
'rgba(54, 158, 64, 0.2)',
'rgba(255, 125, 64, 0.2)',
'rgba(75, 165, 192, 0.2)'
],
borderWidth: 1
}]
},
});
});
</script>
It worked:
[1]: https://i.stack.imgur.com/9hVuO.png
0๐
You can try:
...
data: {
labels: [{%for data in dictCategory%} {{ data.category }}, {%endfor%}] //loop through queryset,
datasets: [{
label: '# of users',
data: [{%for data in dictCategory%}{{ data.count }},{%endfor%}],
...
the problem is that keys here are category and count, and values are their values. so when you try to get keys, you get category
and count
.
Another way to do it is that:
...
$(document).ready(function(){
dictCategory = {{dictCategory}}
labels = []
data = []
for (i = 0; i < dictCategory.length; i++){
labels.append(item.category);
data.append(item.count);
}
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: labels,
datasets: [{
label: '# of users',
data: data
...
Source:stackexchange.com