dygraphs icon indicating copy to clipboard operation
dygraphs copied to clipboard

Positive and negative values in stacked graphs issue

Open marekrojicek opened this issue 7 years ago • 1 comments

Hi, there is an issue around stacked graphs when you have positive and negative values. It seems like the stack is constructed as a simple sum of all the different values, rather than stacking all positive values above the 0 x-axis and all negative values below the 0 x-axis. This means that if you have e.g. one large positive value (e.g. +10) and one small negative value (e.g. -2), then the negative value will appear at +8 rather than appearing at -2.

Please find an example below. This uses the bar chart plotter as this would be the more common use case but the issue is the same when using a simple line graph.

Thank you in advance for looking into this.

library(dygraphs)
library(xts)

data <- xts(matrix(c(200, 100, 100, 200, -100, -200, 100, -200, 400, 300, -300, -100), nrow = 3, ncol = 4), 
               order.by = as.Date(c("2018-01-01", "2018-02-01", "2018-03-01")))

barChartPlotter <- "function barChartPlotter(e) {
           var ctx = e.drawingContext;
var points = e.points;
var y_bottom = e.dygraph.toDomYCoord(0);

ctx.fillStyle = e.color;

// Find the minimum separation between x-values.
// This determines the bar width.
var min_sep = Infinity;
for (var i = 1; i < points.length; i++) {
var sep = points[i].canvasx - points[i - 1].canvasx;
if (sep < min_sep) min_sep = sep;
}
var bar_width = Math.floor(2.0 / 3 * min_sep);

// Do the actual plotting.
for (var i = 0; i < points.length; i++) {
var p = points[i];
var center_x = p.canvasx;

ctx.fillRect(center_x - bar_width / 2, p.canvasy,
bar_width, y_bottom - p.canvasy);

ctx.strokeRect(center_x - bar_width / 2, p.canvasy,
bar_width, y_bottom - p.canvasy);
}
}"

dygraph(data) %>%
  dyOptions(stackedGraph = TRUE, plotter = barChartPlotter)

marekrojicek avatar Jun 29 '18 18:06 marekrojicek

@breakthebeat , did you ever find a solution for this?

majazaloznik avatar Apr 28 '23 11:04 majazaloznik