Jeremy Thomas
Jeremy Thomas

Reputation: 6674

Rails dual axis using Chartkick and chart js

I am trying to use Chartkick with the Chart.js adapter and am trying to make a simple dual-axis chart but none of my settings seem to work. I know it's just a formatting issue but I feel as though I've tried everything with no luck.

My data is this format and as you can see I've added the yAxisID to each dataset.

@consultations = [{:name=>nil,
  :data=>
   [[Fri, 01 Dec 2017, 346],
    [Mon, 01 Jan 2018, 99],
    [Thu, 01 Feb 2018, 282],
    [Thu, 01 Mar 2018, 267],
    [Sun, 01 Apr 2018, 335],
  :yAxisID=>"y"},
 {:name=>"check with spouse",
  :data=>
   [[Fri, 01 Dec 2017, 0],
    [Mon, 01 Jan 2018, 1],
    [Thu, 01 Feb 2018, 9],
    [Thu, 01 Mar 2018, 13],
    [Sun, 01 Apr 2018, 19],
  :yAxisID=>"y1"},
 {:name=>"too busy",
  :data=>
   [[Fri, 01 Dec 2017, 0],
    [Mon, 01 Jan 2018, 1],
    [Thu, 01 Feb 2018, 0],
    [Thu, 01 Mar 2018, 3],
    [Sun, 01 Apr 2018, 1],
  :yAxisID=>"y1"},
 {:name=>"made post consultation",
  :data=>
   [[Fri, 01 Dec 2017, 0],
    [Mon, 01 Jan 2018, 2],
    [Thu, 01 Feb 2018, 4],
    [Thu, 01 Mar 2018, 14],
    [Sun, 01 Apr 2018, 12],
  :yAxisID=>"y1"}
  ...
]

When I plot the chart, the legend position updates, but there is only 1 y-axis and all data is plotted against it are unchanged:

<%= line_chart @consultations, legend: true, library: {
    legend: { position: 'top' },
    scales: {
        y: {
            type: 'linear',
            display: true,
            position: 'left',
        },
        y1: {
            type: 'linear',
            display: true,
            position: 'right',
        }
    }
}, id: 'consult-chart', adapter: 'chartjs' %>

Upvotes: 0

Views: 1189

Answers (1)

Piet
Piet

Reputation: 366

You need to make sure to pass the scales in the correct format. See this example of using Axis IDs in the docs. I.e. scales needs to contain a yAxes field with an array of the axis objects and each axis object has an id field that matches one of the IDs from your datasets.

So, you should change your code to something like this:

<%= line_chart @consultations, legend: true, library: {
    legend: { position: 'top' },
    scales: {
        yAxes: [
            {
                id: 'y',
                type: 'linear',
                display: true,
                position: 'left',
            },
            {
                id: 'y1',
                type: 'linear',
                display: true,
                position: 'right',
            }
        ]
    }
}, id: 'consult-chart', adapter: 'chartjs' %>

Upvotes: 3

Related Questions