我有以下时间序列(数据从 2012-01-01 开始到 2012-12-31 结束):
ts.rmean ts.rmax
2012-01-01 3.163478 5.86
2012-01-02 3.095909 4.67
2012-01-03 3.112000 6.01
2012-01-04 2.922800 5.44
2012-01-05 2.981154 5.21
2012-01-06 3.089167 5.26
我正在使用 dygraph for R 进行绘图:
library(dplyr)
library(digraphs)
dygraph(data.in, main = "Title") %>%
dySeries("ts.rmean", drawPoints = TRUE, color = "blue") %>%
dySeries("ts.rmax", stepPlot = TRUE, fillGraph = TRUE, color = "red") %>%
dyHighlight(highlightSeriesOpts = list(strokeWidth = 3))
是否可以在 x 轴上仅显示月份而不是月份年份(例如“1 月 12 日”)?而且,在情节的图例中,而不是显示月日年(例如 2012 年 1 月 1 日)来显示月日?
最佳答案
您可以使用 javascript 函数修改所有轴标签并设置值的格式。
例如:
library(dygraphs)
library(xts)
library(htmlwidgets)
#the axis label is passed as a date, this function outputs only the month of the date
getMonth <- 'function(d){
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun","Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
return monthNames[d.getMonth()];
}'
#the x values are passed as milliseconds, turn them into a date and extract month and day
getMonthDay <- 'function(d) {
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun","Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
date = new Date(d);
return monthNames[date.getMonth()] + " " +date.getUTCDate(); }'
#set the value formatter function and axis label formatter using the functions above
#they are wrapped in JS() to mark them as javascript
dygraph(data.in, main = "Title") %>%
dySeries("ts.rmean", drawPoints = TRUE, color = "blue") %>%
dySeries("ts.rmax", stepPlot = TRUE, fillGraph = TRUE, color = "red") %>%
dyHighlight(highlightSeriesOpts = list(strokeWidth = 3)) %>%
dyAxis("x",valueFormatter=JS(getMonthDay), axisLabelFormatter=JS(getMonth))
关于r - 如何在 dygraphs 中为 R 设置 x 轴以仅显示月份,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28915328/