I learned how to create a custom plotter for Dygraphs from here: Create a barplot in R using dygraphs package thanks to: https://stackoverflow.com/users/1466144/kero
This is what I'm able to create:
library(xts)
library(dygraphs)
library(lubridate)
mychart <- xts(matrix(c(5,-4,0,-3,2,-5,3,4,-4,2),nrow=5,ncol=2),
order.by = lubridate::ymd(c("2015-01-01", "2015-02-01", "2015-03-01",
"2015-04-01", "2015-05-01")))
colnames(mychart) <- c('Blue','Orange')
dygraph(mychart) %>%
dyOptions(colors= c('#0c93d6','#f5b800'), stackedGraph=TRUE,
plotter =
"function barChartPlotter(e) {
var ctx = e.drawingContext;
var points = e.points;
var y_bottom = e.dygraph.toDomYCoord(0);
var bar_width = 2/3 * (points[1].canvasx - points[0].canvasx);
ctx.fillStyle = e.color;
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);
}
}")
but I face 2 problems:
(1) Chart is cropped at the beginning and at the end of the x-axis. How do I fix that?
(2) When a negative value and a positive value are present, I'd like it to show both values starting from zero origin. An example of this would be the implementation of chart.StackedBar from the PerformanceAnalytics package.
Here it is an example of how I'd like my Dygraphs chart to look like regarding positive and negative values addition:
library(PerformanceAnalytics)
chart.StackedBar(mychart, colorset=c('#0c93d6','#f5b800'))
I find Dygraphs for R really amazing, but I'm a little lost with the javascript. Thanks a lot!