Magofoco
Magofoco

Reputation: 5446

Chartkick - Stacked vertical graph in percentage

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"

Upvotes: 2

Views: 934

Answers (1)

elvinas
elvinas

Reputation: 584

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.

Upvotes: 3

Related Questions