pfuhlert
pfuhlert

Reputation: 531

Create a barplot in R using dygraphs package

Is there a way to use different kinds of plots with dygraphs in R like on the dygraphs website itself http://dygraphs.com/tests/plotters.html? Is there a way to access these when using R? A simple example taken from the dygraphs for R website would look like:

library(dygraphs)
library(dplyr)
lungDeaths <- cbind(mdeaths, fdeaths)
dygraph(lungDeaths)
# How to choose a different type of plot?

/edit. So I found out that you can use custom plotters with dygraphs like on here: http://blog.dygraphs.com/2012/08/introducing-custom-plotters.html. Is there any way to get that in R?

Upvotes: 8

Views: 5854

Answers (2)

KERO
KERO

Reputation: 705

I used plotter in dyOptions to create a bar chart. I just copied the barChartPlotter function from the dygraphs blog. http://blog.dygraphs.com/2012/08/introducing-custom-plotters.html

library(xts)
library(dygraphs)
library(lubridate)

graph_data <- xts(x = c(1,2,3,4), order.by = lubridate::ymd(c("2015-01-01", "2015-02-01", "2015-03-01", "2015-04-01")))
names(graph_data) <- "value"

dygraph(graph_data) %>%
  dyOptions(useDataTimezone = TRUE, plotter = 
              "function barChartPlotter(e) {
                var ctx = e.drawingContext;
                var points = e.points;
                var y_bottom = e.dygraph.toDomYCoord(0);  // see     http://dygraphs.com/jsdoc/symbols/Dygraph.html#toDomYCoord

                // This should really be based on the minimum gap
                var bar_width = 2/3 * (points[1].canvasx - points[0].canvasx);
                ctx.fillStyle = e.color;

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

                  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);
                }
              }")

Upvotes: 8

Bechyň&#225;k Petr
Bechyň&#225;k Petr

Reputation: 795

Try the rCharts and NVD3. It is not possible to zoom in the graphs, but IMO it is more fancy and some of selection features are cool.

Upvotes: 2

Related Questions