Giter Site home page Giter Site logo

chartkick's Introduction

Chartkick

Create beautiful JavaScript charts with one line of Ruby. No more fighting with charting libraries!

See it in action

🔥 For admin charts and dashboards, check out Blazer

💕 A perfect companion to Groupdate, Hightop, and ActiveMedian


Have a minute? Take the 2019 Chartkick Survey


Quick Start

Add this line to your application's Gemfile:

gem "chartkick"

In application.js, add:

//= require Chart.bundle
//= require chartkick

This sets up Chartkick with Chart.js. For other charting libaries, see detailed instructions.

Charts

Line chart

<%= line_chart User.group_by_day(:created_at).count %>

Pie chart

<%= pie_chart Goal.group(:name).count %>

Column chart

<%= column_chart Task.group_by_hour_of_day(:created_at, format: "%l %P").count %>

Bar chart

<%= bar_chart Shirt.group(:size).sum(:price) %>

Area chart

<%= area_chart Visit.group_by_minute(:created_at).maximum(:load_time) %>

Scatter chart

<%= scatter_chart City.pluck(:size, :population) %>

Geo chart - Google Charts

<%= geo_chart Medal.group(:country).count %>

Timeline - Google Charts

<%= timeline [
  ["Washington", "1789-04-29", "1797-03-03"],
  ["Adams", "1797-03-03", "1801-03-03"],
  ["Jefferson", "1801-03-03", "1809-03-03"]
] %>

Multiple series

<%= line_chart @goals.map { |goal|
    {name: goal.name, data: goal.feats.group_by_week(:created_at).count}
} %>

or

<%= line_chart Feat.group(:goal_id).group_by_week(:created_at).count %>

Say Goodbye To Timeouts

Make your pages load super fast and stop worrying about timeouts. Give each chart its own endpoint.

<%= line_chart completed_tasks_charts_path %>

And in your controller, pass the data as JSON.

class ChartsController < ApplicationController
  def completed_tasks
    render json: Task.group_by_day(:completed_at).count
  end
end

For multiple series, add chart_json at the end.

render json: Task.group(:goal_id).group_by_day(:completed_at).count.chart_json

Options

Id, width, and height

<%= line_chart data, id: "users-chart", width: "800px", height: "500px" %>

Min and max values

<%= line_chart data, min: 1000, max: 5000 %>

min defaults to 0 for charts with non-negative values. Use nil to let the charting library decide.

Colors

<%= line_chart data, colors: ["#b00", "#666"] %>

Stacked columns or bars

<%= column_chart data, stacked: true %>

Discrete axis

<%= line_chart data, discrete: true %>

Label (for single series)

<%= line_chart data, label: "Value" %>

Axis titles

<%= line_chart data, xtitle: "Time", ytitle: "Population" %>

Straight lines between points instead of a curve

<%= line_chart data, curve: false %>

Hide points

<%= line_chart data, points: false %>

Show or hide legend

<%= line_chart data, legend: false %>

Specify legend position

<%= line_chart data, legend: "bottom" %>

Defer chart creation until after the page loads

<%= line_chart data, defer: true %>

Donut chart

<%= pie_chart data, donut: true %>

Prefix, useful for currency - Chart.js, Highcharts

<%= line_chart data, prefix: "$" %>

Suffix, useful for percentages - Chart.js, Highcharts

<%= line_chart data, suffix: "%" %>

Set a thousands separator - Chart.js, Highcharts

<%= line_chart data, thousands: "," %>

Set a decimal separator - Chart.js, Highcharts

<%= line_chart data, decimal: "," %>

Show a message when data is empty

<%= line_chart data, messages: {empty: "No data"} %>

Refresh data from a remote source every n seconds

<%= line_chart url, refresh: 60 %>

You can pass options directly to the charting library with:

<%= line_chart data, library: {backgroundColor: "#eee"} %>

See the documentation for Chart.js, Google Charts, and Highcharts for more info.

To customize datasets in Chart.js, use:

<%= line_chart data, dataset: {borderWidth: 10} %>

You can pass this option to individual series as well.

Global Options

To set options for all of your charts, create an initializer config/initializers/chartkick.rb with:

Chartkick.options = {
  height: "400px",
  colors: ["#b00", "#666"]
}

Customize the html

Chartkick.options[:html] = '<div id="%{id}" style="height: %{height};">Loading...</div>'

You capture the JavaScript in a content block with:

Chartkick.options[:content_for] = :charts_js

Then, in your layout:

<%= yield :charts_js %> <!-- Rails -->
<%= yield_content :charts_js %> <!-- Padrino -->

This is great for including all of your JavaScript at the bottom of the page.

Data

Pass data as a Hash or Array

<%= pie_chart({"Football" => 10, "Basketball" => 5}) %>
<%= pie_chart [["Football", 10], ["Basketball", 5]] %>

For multiple series, use the format

<%= line_chart [
  {name: "Series A", data: series_a},
  {name: "Series B", data: series_b}
] %>

Times can be a time or a string (strings are parsed)

<%= line_chart({20.day.ago => 5, "2013-05-07 00:00:00 UTC" => 7}) %>

Multiple Series

You can pass a few options with a series:

  • name
  • data
  • color
  • dataset - Chart.js only
  • points - Chart.js only
  • curve - Chart.js only

Code

If you want to use the charting library directly, get the code with:

<%= line_chart data, code: true %>

The code will be logged to the JavaScript console.

Note: JavaScript functions cannot be logged, so it may not be identical.

Download Charts

Chart.js only

Give users the ability to download charts. It all happens in the browser - no server-side code needed.

<%= line_chart data, download: true %>

Set the filename

<%= line_chart data, download: {filename: "boom"} %>

Note: Safari will open the image in a new window instead of downloading.

Set the background color

<%= line_chart data, download: {background: "#ffffff"} %>

Installation

Add this line to your application's Gemfile:

gem "chartkick"

Next, choose your charting library.

Charting Libraries

Note: In the instructions below, application.js must be included before the charts in your views, unless using the :content_for option.

Chart.js

In application.js, add:

//= require Chart.bundle
//= require chartkick

Google Charts

In application.js, add:

//= require chartkick

In your views, before application.js, add:

<%= javascript_include_tag "https://www.gstatic.com/charts/loader.js" %>

Highcharts

Download highcharts.js into vendor/assets/javascripts (or use yarn add highcharts in Rails 5.1+).

In application.js, add:

//= require highcharts
//= require chartkick

Works with Highcharts 2.1+

Webpacker

For Webpacker, use Yarn to install the JavaScript libraries:

yarn add chartkick chart.js # or highcharts

Then include them in your pack.

import Chartkick from "chartkick";
window.Chartkick = Chartkick;

// for Chart.js
import Chart from "chart.js";
Chartkick.addAdapter(Chart);

// for Highcharts
import Highcharts from "highcharts";
Chartkick.addAdapter(Highcharts);

// for Google Charts
// just include https://www.gstatic.com/charts/loader.js in your views

You pack must be included before the charts in your views, unless using the :content_for option.

Sinatra and Padrino

You must include chartkick.js manually. Download it here

<script src="chartkick.js"></script>

Localization

To specify a language for Google Charts, add:

Chartkick.configure({language: "de"});

after the JavaScript files and before your charts.

Multiple Libraries

If more than one charting library is loaded, choose between them with:

<%= line_chart data, adapter: "google" %> <!-- or highcharts or chartjs -->

JavaScript API

Access a chart with:

var chart = Chartkick.charts["chart-id"]

Get the underlying chart object with:

chart.getChartObject()

You can also use:

chart.getElement()
chart.getData()
chart.getOptions()
chart.getAdapter()

Update the data with:

chart.updateData(newData)

You can also specify new options:

chart.setOptions(newOptions)
// or
chart.updateData(newData, newOptions)

Refresh the data from a remote source:

chart.refreshData()

Redraw the chart with:

chart.redraw()

Loop over charts with:

Chartkick.eachChart( function(chart) {
  // do something
})

Content Security Policy (CSP)

Check out how to configure CSP

No Ruby? No Problem

Check out chartkick.js

Tutorials

Upgrading

3.0

Breaking changes

  • Removed support for Rails < 4.2
  • Removed chartkick.js from asset precompile (no longer needed)
  • Removed xtype option - numeric axes are automatically detected
  • Removed window.Chartkick = {...} way to set config - use Chartkick.configure instead
  • Removed support for the Google Charts jsapi loader - use loader.js instead

2.0

Breaking changes

  • Chart.js is now the default adapter if multiple are loaded - yay open source!
  • Axis types are automatically detected - no need for discrete: true
  • Better date support - dates are no longer treated as UTC

Credits

Chartkick uses iso8601.js to parse dates and times.

History

View the changelog

Chartkick follows Semantic Versioning

Contributing

Everyone is encouraged to help improve this project. Here are a few ways you can help:

chartkick's People

Contributors

ankane avatar detry322 avatar ceclinux avatar guymaliar avatar timleppard avatar printercu avatar black-snow avatar novtopro avatar lavode avatar tarraschk avatar ombr avatar kylemathews avatar kirkelifson avatar maclover7 avatar jeanmartin avatar federomero avatar eliotsykes avatar dpayonk avatar cbdileo avatar

Watchers

Eyal Toledano avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.