Draw a pie chart with Chart.js

Create a simple pie chart from database values ​​with chart.js Graph of winning / losing probability that is common in sports competitions (setting of up to 100%) スクリーンショット 2021-01-20 16.27.41.png

Database

forecasts table num is the win probability of win_school win_school is the team that is expected to win lose_school is a team that is expected to lose

id num user_id win_school lose_school
1 60 1 A school B school

controller

Setting to fetch data with id 1

def show
  @forecast = Forecast.find(params[:id])
end

html file

<div class="win"><%= @forecast.win_school %></div><!--A school-->
<div class="lose"><%= @forecast.lose_school %></div><!--B school-->
<div class="win-rate"><%= @forecast.num %></div><!-- 60 -->
<div class="pie"><!--Graph drawing part-->
  <div style="width:60%; height:60%";><canvas id="PieChart"></canvas></div>
</div>
<%= javascript_pack_tag 'forecast' %> <!--js read-->

If you want to hide it, use hidden.

<div hidden class="win">

js file

app > javascript > packs > forecast.js

var ctx = document.getElementById("PieChart");
var win = document.getElementsByClassName("win").textContent //Get value from class name win(A school)
var lose = document.getElementsByClassName("lose").textContent //Get value from class name lose(B school)
var winnum = document.getElementsByClassName("win-rate").textContent  //Class name win-Get value from rate(60)
var PieChart = new Chart(ctx, {
  type: 'pie', //Meaning that the type of graph is a pie chart
  data: {
    labels: [win,lose], //Pie chart label(Pie chart A school,Where it is displayed as B school)
    datasets: [{
      backgroundColor: [ //Pie chart color
        "#FF0000", //First color(Label win)Is red
        "#33CCFF", //Second color(Label lose)Is light blue
      ],
      data: [winnum,100-winnum] //Graph values ​​See below
    }]
  },
  options: { //Optional customization?
    title: {
      display: true,
      text: 'Victory probability'//Graph title
    }
  }
});

data: is inserting a value into the graph Since the variable winnum contains 60, the second is 100-60 and 40 is entered. The winning percentage of A school is 60%, and the winning percentage of B school is 40%.

.js


data: [winnum,100-winnum]

This time I got the value from the html file If you want to get it from the controller, I think you should use gon

Recommended Posts

Draw a pie chart with Chart.js
Draw a gradient with CAGradientLayer
Java creates a pie chart in Excel
Draw a graph with Sinatra and Chartkick
Create a simple bar chart with MPAndroidChart
[Ruby on Rails] Create a pie chart for each column with Chartkick
[Swift 5] Draw a line.
[Java] Draw a simple pattern
A story stuck with NotSerializableException