2

I am building a vertical percentage graph following the google instruction: https://developers.google.com/chart/interactive/docs/gallery/barchart#StackedBars

This is how it should look like:

Good final graph

However, this is how it look right now. Wrong one

I am using the same data as the one of google.

my_graph_controllers

@data = [
        ['Genre', 'Fantasy & Sci Fi', 'Romance', 'Mystery/Crime', 'General',
         'Western', 'Literature', { role: 'annotation' } ],
        ['2010', 10, 24, 20, 32, 18, 5, ''],
        ['2020', 16, 22, 23, 30, 16, 9, ''],
        ['2030', 28, 19, 29, 30, 12, 13, '']
      ]

view/my_graph.html.erb

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

<div class="container">

  <%= bar_chart @data, isStacked: true, isStacked: "percentage" %>

</div>

assets/javascripts/application.js

//= require rails-ujs
//= require_tree .
//= require Chart.bundle
//= require chartkick
//= require highcharts

gemfile

gem "chartkick"
Magofoco
  • 5,098
  • 6
  • 35
  • 77
  • 1
    Have you tried just `<%= bar_chart @data, stacked: true %>`? Chartkick seems to have made some options 'native'. – elvinas Feb 05 '19 at 08:15

1 Answers1

3

So the trick is to transform the data a bit.

@data = [
      {
        name: "Fantasy & Sci Fi", 
        data: [["2010", 10], ["2020", 16], ["2030", 28]]
      },
      {
        name: "Romance", 
        data: [["2010", 24], ["2020", 22], ["2030", 19]]
      },
      {
        name: "Mystery/Crime", 
        data: [["2010", 20], ["2020", 23], ["2030", 29]]
      }
    ]

And this works like a charm then:

<%= bar_chart @data, stacked: true %>

I have found the answer in an older question over here.

However, if you want to do the percentage stack, you need to use the library hash for that.

<%= bar_chart @data, adapter: 'google', library: { isStacked: 'percent' } %>

P.s. Notice that it should be either true or 'percent' for the isStacked. More information here.

elvinas
  • 554
  • 6
  • 19
  • Many thanks. It works. I have one question more and one comment. Question: do you know how to display it in % as the first imaged in my question? I tried with `<%= bar_chart @data, stacked: true, stacked: 'percentage %> ` with little success. Comment: fix your reply modifying `@test_data` as `@data´ or it does not work. – Magofoco Feb 05 '19 at 14:16
  • 1
    With a bit of tweaking I got this to work: `<%= bar_chart @data, adapter: 'google', library: { isStacked: 'percent' } %>` – elvinas Feb 05 '19 at 21:42
  • Many thanks, you are helping a lot! Last question, I am trying to rotate the graph (basically I want it vertical and not horizontal, as it is now) but I am not able to find the command on the documentation. – Magofoco Feb 06 '19 at 15:22
  • 1
    Then it's called a **column_chart** instead of a **bar_chart**. Everything else stays the same. :) – elvinas Feb 07 '19 at 09:49