Charts and Graphs

Episode #55 by David Kimura

Summary

Learn how to use one of three charting libraries, Chart.js, Highcharts, or Google Charts, using the Chartkick gem to create simple and unobtrusive charts in your application.
rails javascript view 7:42

Resources

Summary

# Gemfile
gem 'chartkick'

Chart.js

# application.js
//= require Chart.bundle
//= require chartkick

Highcharts
You will need to download highcharts javascript file and place it within the vendor/assets/javascripts folder.

# application.js
//= require highcharts
//= require chartkick

Google Charts

# application.js
//= require chartkick

# app/views/layouts/application.rb
<%= javascript_include_tag "https://www.google.com/jsapi" %>

# view
<%= line_chart @product.purchases.group(:purchased_on).sum(:purchased_price),
               id: 'purchase',
               library: { animation: { easing: 'easeOutQuad' }} %>

<%# line_chart({ 20.day.ago => 5, 10.day.ago => 10, "2016-010-07 00:00:00 UTC" => 7 }) %>

<%# pie_chart [["Football", 10], ["Basketball", 5]] %>

Interacting with a chart:

# application.js
$(document).on('turbolinks:load', function(event) {
  var chart = Chartkick.charts['purchase'].getChartObject();
  setInterval(function(){
    var indexToUpdate = Math.round(Math.random() * 30);
    chart.data.datasets[0].data[indexToUpdate] = Math.random() * 100;
    chart.update();
  }, 1);
});

Chart Options

# config/initializers/chartkick.rb
Chartkick.options = {
  colors: ['#41060f', "pink"]
}