Skip to content

Rendering a Chart with AmCharts.rb

Daniel Vandersluis edited this page Apr 5, 2014 · 2 revisions

Note: The code demonstrated on this page is available as part of the compendium_demo project, which you can clone and play with yourself. This sample application gives a simple report outlining spending over a given period.

This section makes use of the amcharts.rb gem to render charts. In order to render a chart, you must first add the chart provider to your Gemfile:

gem 'compendium-amcharts'

If you have multiple chart providers installed, create an initializer to tell Compendium to use AmCharts:

Compendium.configure do |config|
  config.chart_provider = :AmCharts
end

Charts are rendered by specifying what type of chart you wish to use (:serial for line/column/bar charts, :pie, :funnel, :gauge, :radar, :xy), and a setup block to specify options. See the amcharts.rb documentation for more information about how to configure your chart.

Code Output
query.render_chart(self, :pie) do |c|
  add_title "Spending Per Month"

c.dimensions = "600x400" c.label_radius = 15 c.margin_bottom = -100 c.margin_top = -100 c.margin_left = -50 c.margin_right = 0

c.colors = %w(#0E51A7 #640CAB #4DDE00) c.number_formatter = { precision: 2, decimalSeparator: '.', thousandsSeparator: ',' } end

query.render_chart(self, :serial) do |c|
  add_title "Spending Per Day"
  c.dimensions = "800x400"
  c.data_date_format = "YYYY-MM-DD"

graphs.new(:amount, :smoothedLine) do |g| g.id = "amount" g.title = "Amount" end

category_axis do |a| a.parse_dates = true a.grid_alpha = 0.1 a.axis_alpha = 0 a.grid_position = 'start' a.position = 'top' end

scrollbar do |s| s.graph = 'amount' s.scrollbar_height = 30 end

cursor {} end

####Loading Remote Data See Remote Data Charts for information on how to set up a remote chart.

With AmCharts.rb, you can set up a remote chart which defers loading until requested, by adding the following to your setup block:

query.render_chart(self, :serial, remote: true) do |c|
  data_source.defer!
end

A deferred chart will be created but will not update its data set until requested (in order to do so, you will need to get a reference to the AmCharts chart object) via Javascript:

chart = AmCharts.charts[0] // or get the chart some other way
chart.remoteProvider.load()

####Notes

  • By default, the amcharts helper provided by amcharts.rb, which is used by Compendium to render a chart, adds the necessary javascript files and stylesheets, using content_for. If your chart isn't rendering, ensure that you have yield :javascript and yield :stylesheets in your layout.
  • A chart will not render if a height and width is not defined. Either set chart.dimensions or chart.height and chart.width in your chart setup block.
  • See the AmCharts API documentation for more details about chart options.
Clone this wiki locally