使用dygraphs包在R中创建一个条形图

时间:2015-04-17 11:46:00

标签: r bar-chart dygraphs

有没有办法在dygraphs网站本身http://dygraphs.com/tests/plotters.html中使用不同类型的情节与R中的dygraph?使用R时有没有办法访问这些?从R网站的dygraph中获取的一个简单示例如下:

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

/编辑。所以我发现你可以在这里使用带有dygraph的自定义绘图仪:http://blog.dygraphs.com/2012/08/introducing-custom-plotters.html。有没有办法在R中得到它?

2 个答案:

答案 0 :(得分:8)

我在dyOptions中使用绘图仪来创建条形图。我刚刚从dygraphs博客中复制了barChartPlotter函数。 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);
                }
              }")

答案 1 :(得分:2)

尝试rChartsNVD3。不可能放大图表,但IMO更加花哨,一些选择功能很酷。