bobbingwide / sb-chart-block

Chart block for Gutenberg
GNU General Public License v3.0
6 stars 0 forks source link

Multi axis line chart #22

Closed misaki-web closed 1 year ago

misaki-web commented 2 years ago

Here's an example of multi axis line chart in the Chart.js documentation:

multi-axis-line-chart

Scales settings must have y and y1, and each dataset must be linked to a specific axis. Here's a very quick and dirty way just to get an idea of what's needed:

# In the `functions.php` theme file:
function chartjs_filter($output, $tag, $atts) {
    if ($tag == 'chartjs') {
        $custom_scales = <<<SCALES
            scales: {
              y: {
                type: 'linear',
                display: true,
                position: 'left',
              },
              y1: {
                type: 'linear',
                display: true,
                position: 'right',
              },
            }
        SCALES;
        $output = str_replace('}} };', '}},' . $custom_scales . '};', $output);
        $output = str_replace('datasets:[{', 'datasets:[{"yAxisID": "y",', $output);
        $output = str_replace('"showLine":true}]};', '"showLine":true,"yAxisID":"y1"}]};', $output);
    }

    return $output;
}
add_filter('do_shortcode_tag', 'chartjs_filter', 10, 3);

The shortcode to test:

[chartjs type="line"]Year,Dataset1,Dataset2
2016,125,2451.32
2017,158,1878.00
2018,215,1256.32
2019,325,34521.32
2020,500,1896.32
2021,251.32,2725.32[/chartjs]

The result:

multi-axis-line-chart-demo

bobbingwide commented 1 year ago

Reopening to enable the multi axis logic to be made active in the block editor.

In the editor code each object in datasets needs to have the yAxisID attribute set to "y" or "y1".

Also when multiple axes are required options.scales.y1 needs to be set similar to scales.y but with "position":"right"

eg

"y1":{"beginAtZero":true,"position":"right","stacked":false}}};
bobbingwide commented 1 year ago

Here's a screenshot of the front-end for 4 charts with identical values but different setttings for the y-axes. image

Here's a screenshot of the block editor for the same 4 charts.

image

Notes:

Current limitations

bobbingwide commented 1 year ago

The x-axis font size is not being applied on the front end.

That's because we haven't completed #21

bobbingwide commented 1 year ago

Note: If you deselect all the lines that are used for a particular y-axis the scales are reset. This is standard chart.js behaviour that probably isn't easy to change.

image image

When there are more than 2 lines the result of deselection is quite interesting.

bobbingwide commented 1 year ago

The block editor should support charts where the yAxes attribute is not set. It currently produces an error Cannot read properties of undefined (reading 'includes') at

if ( this.attributes.yAxes.includes( 'y1' ) ) {
bobbingwide commented 1 year ago

Deliveredin v1.2.0