2015-07-10 88 views
2

我在R中使用“dygraphs”包来绘制条形图并为所有酒吧分配绿色。当我在R中显示图表时,事情是完全正常的,但是当我尝试在Web浏览器中显示它们时,所有的条形图都会变黑。下面是代码(包括JavaScript的一个片段,因为谷歌说,我可以用它来绘制使用dygraph条形图):R中的Dygraphs在浏览器中查看时不显示颜色

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

df <- data.frame(date = as.Date(13800:13810, origin = "1970-01-01"), 
        n = 1:11) 

graph_data <- xts(x = 1:10, order.by = as.Date(13801:13810, origin = "1970-01-01")) 

dygraph(graph_data) %>% 
    dyOptions(useDataTimezone = TRUE, 
       colors = c("008000"), 
       plotter = 
        "function barChartPlotter(e) { 
      var ctx = e.drawingContext; 
      var points = e.points; 
      var y_bottom = e.dygraph.toDomYCoord(0); 

      var bar_width = 1/2 * (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; // 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); 
      } 
      }") 

我可能必须使用dygraphs画吧,因为它是快,吸引了成千上万的酒吧...

任何帮助表示赞赏!

+0

你如何在浏览器中显示图表? – Shiva

+0

通常两种情况。如果我在R中使用Shiny而不是RStudio,则输出为HTML文件,并在浏览器中显示。在这种情况下,dygraphs的颜色是错误的,但由RStudio创建的窗口在颜色方面完全没问题。另一种情况是,当我在RStudio中绘制dygraph时,在“查看器”中总是有一个选项,您可以通过单击第二个最右边的按钮在浏览器中显示输出。我不确定如何使用Javascript在浏览器中显示dygraph,但我认为有一种方法可以将图形放入HTML文件中。 –

回答

1

您只是在设置颜色时缺少'#'。检查 colors = c("008000")一行。它应该是colors = c("#008000")

+0

感谢您的建议!我刚刚尝试过,但问题仍然存在。可能在其他地方也(也)破碎... –

+0

这是在我的机器完美的工作!我正在使用上面公布的代码和我建议的更改(只是插入#)。 – Shiva