Search code examples
javascripthtmlspring-bootthymeleafplotly

How to use this simple Plotly?


I want to make a simple graphic for my top 5 courses with name and booked times.

Every data is based on different situations.

My html site code:

            <tr th:each="m : ${topCourses }">      
                <td th:text="${m.coursName}"></td>  
                <td th:text="${m.bookedTimes}"></td>
            </tr>

and I found this plotly code and I'm new to working with JavaScript.

var data = [
  {
    x: ['giraffes', 'orangutans', 'monkeys'],
    y: [20, 14, 23],
    type: 'bar'
  }
];

Plotly.newPlot('myDiv', data);

This is an example from plotly.

How can I set my 5 course's name on x, and booked times on y? (this data is automatic changing everyday)


Solution

  • This should work for you:

    <script th:inline="javascript" th:with="courseNames=${topCourses.![courseName]},bookedTimes=${topCourses.![bookedTimes]}">
      var courseNames = /*[[${courseNames}]]*/ [];
      var bookedTimes = /*[[${bookedTimes}]]*/ [];
    
      var data = [{
        x: courseNames,
        y: bookedTimes,
        type: 'bar'
      }];
    
      Plotly.newPlot('myDiv', data);
    </script>
    

    I'm creating 2 temporary Lists -- courseNames and bookedTimes (using collection projection to create them from the original List), and then using JavaScript inlining to turn them into JavaScript arrays. Then, just use those variables (instead of hard coded values) and it will create the chart just like you want it.