[Ruby on Rails] Create a pie chart for each column with Chartkick

Introduction

I used chart kick because I wanted to insert a graph in rails. Since the introduction itself is easy, we will describe how to make a pie chart of the aggregated results.

Referenced page -Chartkick official documentation -If you want to handle simple graphs in Rails, use chartkick rather than chart-js-rails -Implement a pie chart at detonation velocity [5 minutes]

environment

ruby 2.5.1 Rails 5.2.4.3

Assumptions and goals

Create a pie chart from the ** opinion column (integer) ** of the ** votes table ** that summarizes the user's opinions. If the value of the opinion column is 1, it is for, and if it is 0, it is the opposite, but it is created with other values and NULL values mixed.

** votes table **

id opinion
1 1
2 1
3 0
4 1
5 0
6 2
7 NULL
8 3
9 NULL
10 0

** Rendering **

pie_A.png

Introduction of Chart kick

Although it is described on the reference page, it will be described again.

Gemfile


gem "chartkick"   #Append

Gemfile


$ bundle install

app/javascript/packs/application.js


//= require chartkick
//= require Chart.bundle  #Add two lines

Reflection on view page

The page to be displayed can be anywhere, but this time I would like to display the graph in index.html.erb of the posts controller.

html.erb:app/views/posts/index.html.erb


<%= pie_chart Vote.group(:opinion).count%>

chart (1).png

It's a graph that you don't really understand what it represents. ..

Therefore, define variables and methods for graphs in the controller file.

app/controllers/posts_controller.rb


  def index
    @opinion = Vote.pluck(:opinion)
    @aggregate = aggregateOpinion(@opinion)
    @sum = sumOpinion(@opinion)
  end

  def aggregateOpinion(array)
    result = [["Agree",0],["Opposition",0],["Neither",0],["No answer",0]]
    array.each do |i|
      if i == 1
        result[0][1] += 1
      elsif i == 0
        result[1][1] += 1
      elsif i == nil
        result[3][1] += 1
      else 
        result[2][1] += 1
      end
    end
    return result
  end

  def sumOpinion(array)
    result = [["Total votes",0],["Number of valid votes",0],["Number of invalid votes",0]]
    array.each do |i|
      if i == nil
        result[2][1] += 1
      else 
        result[1][1] += 1
      end
    end
    result[0][1] = array.length 
    return result
  end

Commentary

Only the target column is fetched as an array with the pluck method. After that, the aggregateOpinion method is used to format the data for a pie chart.

Since the index of the result array is the display order of the pie chart as it is, the parameter is The null value comes last, followed by the so-called "other" (in this case, the name [neither]).

The sumOpinion method is not directly related to the graph, but it is difficult to put the information on the total number of votes on the graph, so it is created separately.

Based on the above contents, I would like to reflect it on the view page again.

html.erb:app/views/posts/index.html.erb


<%= pie_chart @aggregate, width: "500px"%>

chart (2).png

This is no problem, but at the end, the layout and the contents acquired by the sumOpinion method are displayed in the table element, and it is completed.

html.erb:app/views/posts/index.html.erb


<%= pie_chart @aggregate,colors: ["#3333cc","#cc3333","#339966","333"], donut: true , width: "500px"%>
<table border="1" width="500">
  <tr>
    <th>Total votes</th>
    <th>Number of valid votes</th>
    <th>Number of invalid votes</th>
  </tr>
    <tr>
    <th><%=@sum[0][1]%></th>
    <th><%=@sum[1][1]%></th>
    <th><%=@sum[2][1]%></th>
  </tr>
</table> 

pie_A.png

At the end

What did you think. I think I was able to apply it to the method part a little more. .. Of course, chartkick does not only support pie charts, so please check it out. Thank you for watching!

Recommended Posts

[Ruby on Rails] Create a pie chart for each column with Chartkick
[Ruby on Rails] Add a column with a foreign key constraint
Create a development environment for Ruby 3.0.0 and Rails 6.1.0 on Ubuntu 20.04.1 LTS
[Rails] Procedure for linking databases with Ruby On Rails
I made a portfolio with Ruby On Rails
[Ruby on Rails] Implement a pie chart that specifies the percentage of colors
[Introduction] Try to create a Ruby on Rails application
Tutorial to create a blog with Rails for beginners Part 1
Explanation of Ruby on rails for beginners ③ ~ Creating a database ~
Tutorial to create a blog with Rails for beginners Part 2
Tutorial to create a blog with Rails for beginners Part 0
Draw a pie chart with Chart.js
Steps to build a Ruby on Rails development environment with Vagrant
(Ruby on Rails6) Create a function to edit the posted content
Create a large number of records with one command using the Ruby on Rails seeds.rb file
[Ruby on Rails] View test with RSpec
[Rails6] Create a new app with Rails [Beginner]
[Rails withdrawal] Create a simple withdrawal function with rails
Notes on using FCM with Ruby on Rails
Create a simple bar chart with MPAndroidChart
[Ruby on Rails] Controller test with RSpec
Ruby on Rails controller create / delete command
[Rails 5] Create a new app with Rails [Beginner]
[Ruby on Rails] Model test with RSpec
Explanation of Ruby on rails for beginners ①
Beginners create portfolio in Ruby on Rails
How to create a query using variables in GraphQL [Using Ruby on Rails]
How to build a Ruby on Rails environment using Docker (for Docker beginners)
How to build a Ruby on Rails development environment with Docker (Rails 6.x)
How to build a Ruby on Rails development environment with Docker (Rails 5.x)
Validation settings for Ruby on Rails login function
[Rails] rails new to create a database with PostgreSQL
Introducing Rspec with Ruby on Rails x Docker
Building a Ruby environment for classes on Mac
Publish the app made with ruby on rails
[Ruby on Rails] Select2 introduction memo for Webpacker
Create a team chat with Rails Action Cable
Introducing Rspec, a Ruby on Rails test framework
[Ruby on Rails] A memorandum of layout templates
[Ruby on Rails] Try to create a service that makes local cats happy
Build a development environment to create Ruby on Jets + React apps with Docker
(Ruby on Rails6) Creating data in a table
Determine the current page with Ruby on Rails
[Ruby on Rails] Upload multiple images with refile
Docker command to create Rails project with a single blow in environment without Ruby
Build a Ruby on Rails development environment on AWS Cloud9
[Ruby on Rails] Delete s3 images with Active Strage
Create an EC site with Rails 5 ⑨ ~ Create a cart function ~
Run Ruby on Rails RSpec tests with GitHub Actions
[Ruby on Rails] How to change the column name
Create a widget template for iOS14 with Intent Configuration.
[Ruby on Rails] Change URL id to column name
Create a user with an empty password on CentOS7
Solve the N + 1 problem with Ruby on Rails: acts-as-taggable-on
Challenge the settings for developing with vue.js on Rails 6
Explanation of Ruby on rails for beginners ⑥ ~ Creation of validation ~
Explanation of Ruby on rails for beginners ② ~ Creating links ~
(Ruby on Rails6) How to create models and tables
Created RSS / Atom format sitemap with Ruby on Rails
Explanation of Ruby on rails for beginners ⑦ ~ Flash implementation ~
Ruby on Rails Elementary