K Girish
K Girish

Reputation: 31

How to skip weekends on Dygraps x-axis.

I am trying to use DyGraphs to plot stocks data. It is doing perfect job at plotting and zooming the data. But I have gaps in the data as stocks are not traded on holidays. I don't want saturday and sunday's shown on x-axis. I would like to have chart like that on google finance where x axis skips saturday and sunday (dates where there is no data). Is that possible? Can I achieve this result if I play around with the plotter option?

p.s. I wouldn't mind if the graph doesnt zoom upto hour or minute level.

Upvotes: 3

Views: 432

Answers (2)

Julien L
Julien L

Reputation: 1678

It is years later, but I have an easy solution.

Here is the data I use: https://pastebin.com/kbT6gY2u

It is formatted to display as candlesticks (date,open,close,high,low), as I use the plotter found here: http://dygraphs.com/tests/plotters.html however my solution will work with the default plotter.

The principle is this:

  • Push each date in your data to an array, and replace the date by its index. This will remove all the gaps in your data so you can have one continuous chart.
  • Create a custom axisLabelFormatter to convert the index to a date again on the X axis
  • Create a custom valueFormatter to convert the index to a date again on the legend/mouse over

Code example (uses underscore.js and moment.js for code clarity)

var dateIndex   = [];
var data    = _.map(data, function(line, n) {
    dateIndex.push(line[0]); // Save the date to the array
    line[0] = dateIndex.length-1; // Replace the date by the index of the date in the array
    return line;
});
var g = new Dygraph(element, data, {
    axes: {
        x: {
            valueFormatter: function (val, opts, series_name, dygraph) {
                // val is the date, which we have rewritten to the array's index.
                // So here we can exchange it back for the actual date, and format it
                return moment(dateIndex[val]).format("dddd, MMM Do YYYY, h:mm a");
            },
            axisLabelFormatter: function (val, granularity, opts, dygraph) {
                return moment(dateIndex[val]).format("MMM DD");
            }
        }
    }
});

Upvotes: 5

kberg
kberg

Reputation: 375

I've long considered that perhaps we could abstract enough out of Dygraphs to let the axes be defined by more than just linear vs. logarithmic, but the problem is that it could easily become inefficient. Dygraphs is fast, and at times we keep out features to keep it that way. But any ideas would be welcome.

Upvotes: 1

Related Questions