ChartJs How to create multiple doughnut chart using loop

33 Views Asked by At

I'm attempting to create a doughnut chart using a for loop so that I can generate multiple doughnut charts. The scenario is that I'm sending a list of students (List) to the frontend, and I'm aiming to create a donut chart using the students' names and their respective percentages.

I don't have the exact code, but here's a basic outline:

In my controller:

List<Student> listOfStudent = new ArrayList<>();
model.addAttribute("listOfStudent", listOfStudent);

And in the JSP:

<c:forEach var="student" items="${listOfStudent}">

var ctx = document.getElementById("donutChart").getContext('2d');
var myChart = new Chart(ctx, {
  type: 'doughnut',
  data: {
    labels: ["studname1", "studname2", "studname3", "studname4", "studname5", "studname6", "studname7"],
    datasets: [{
      backgroundColor: [
        "#2ecc71",
        "#3498db",
        "#95a5a6",
        "#9b59b6",
        "#f1c40f",
        "#e74c3c",
        "#34495e"
      ],
      data: [12, 19, 3, 17, 28, 24, 7]
    }]
  }
});

In the labels, the value should be the student's name, in donut there will be student percentage , and below the doughnut, there should be the total number of students.

Attached is the reference image for clarification. enter image description here

1

There are 1 best solutions below

2
DeKai On

You will need to parse the data from the list of students into the chart. so you need to replace labels and data accordingly.