我从这里学习了如何为Dygraphs创建自定义绘图仪: Create a barplot in R using dygraphs package 感谢:https://stackoverflow.com/users/1466144/kero
这是我能够创造的:
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);
}
}")
但我面临两个问题:
(1)图表在x轴的开头和末尾被裁剪。我该如何解决这个问题?
(2)当存在负值和正值时,我希望它显示从零原点开始的两个值。这方面的一个例子是PerformanceAnalytics包中的chart.StackedBar的实现。
这是一个例子,说明我对Dygraphs图表的看法是关于正值和负值的补充:
library(PerformanceAnalytics)
chart.StackedBar(mychart, colorset=c('#0c93d6','#f5b800'))
我觉得Dygraphs对于R真的很神奇,但我对javascript有点失落。 非常感谢!