Snippets

Piotr Szrajber Smart M.App - set hour time scale in a time bar chart

Created by Piotr Szrajber last modified
/*
* Smart M.App - set time bar chart scale to "hours"
* 1. disable elasticX, so that the chart reacts to modifications of the scale
* 2. set time scale to "hours"
* 3. tweak the domain in order to display full bars (including the first one and the last one)
* 4. other minor options
* 2018-10-08 Piotr Szrajber <piotr.szrajber@hexagon.com>
*/

function chartsReady(fn) {
    let observer = new MutationObserver(function(mutations, me) {
        let chartWithSvg = document.querySelector(".widget-chart.dc-chart>svg");
        if (chartWithSvg) {
            fn();
            me.disconnect();
        }
    });

    observer.observe(document, {
        childList: true,
        subtree: true
    });
}

function customizeTimeBarChart(chart) {
    var chartM = chart.getChartModel(),
        key = chartM.key[0],
        minDate = chart.dimension().bottom(1)[0][key],
        maxDate = chart.dimension().top(1)[0][key];

    chartM.axis.x.elastic = false;
    chartM.axis.x.xAxisTimeScale = "hours";
    chartM.axis.x.units = 4;
    chartM.axis.x.ticks = 4;
    chartM.axis.x.padding = 0;
    chartM.bar.barPadding = 3;

    chart._setChartModel(chartM);
    chart.x(d3.time.scale().domain([
        d3.time.hour.offset(minDate, -1),
        d3.time.hour.offset(maxDate, 1)
    ]));
    chart.redraw();
}

function applyCustomizations() {
    chartsReady(function() {
        gsp.bi.stage.findWidgets({
            descriptors: [{
                chartM: {
                    chart: "bar"
                }
            }]
        }, function(widgets) {
            var widget = widgets[0];
            if (!widget) return;
            customizeTimeBarChart(widget.chart);
        });
    });
}

applyCustomizations();

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.