nPlot rCharts - 如何获得辅助轴?

时间:2015-05-07 11:11:39

标签: r rcharts

我想绘制2个不同尺度的变量。辅助轴将是我理想的解决方案。有没有人知道如何在rCharts中实现它。

使用Highcharts有相关帖子: rCharts - Adding second y axis to time series 但是我想知道如何在rCharts中使用nPlot来获取它?

library(rCharts)
set.seed(1)
df <- data.frame(date=as.Date("2014-01-01")+1:10,y1=sample(1:200,70),y2=runif(70))

 buildchart <- function(df) {
 plotData<-df
 temp<-aggregate(cbind(y1)~date,data=df,min)
 tabledta<-summaryBy(y2~date,data=df,FUN=sum,keep.names = TRUE) 
 tabledta<-merge(tabledta,temp,by=c("date"),all.x=T)

  filler = expand.grid(date=seq(as.Date(min(tabledta$date)),max(as.Date(tabledta$date)),by='1 day'))
df = merge(filler,
           tabledta,
           by=c('date'),
           all.x=T)
df[is.na(df)]=0
data.melt<-melt(df,id.vars=c('date'),all=TRUE)

p <- nPlot(value ~ date, group = 'variable', data = data.melt, type = 'lineChart')
p$chart(margin=list(left=150))
p$yAxis(showMaxMin = FALSE)
p$xAxis(tickFormat ="#!function(d) {return d3.time.format('%Y-%m-%d')(new Date(d * 24 * 60 * 60 * 1000));}!#")
p
}

buildchart(df)

1 个答案:

答案 0 :(得分:0)

我认为type='multichart'可能是一个好的开始,我发现与保证金和yAxis有些不兼容,但可能有办法解决。您可以在此处找到multichart类型的示例: http://rcharts.readthedocs.org/en/latest/nvd3/create.html#multi-chart

关于你的功能,接下来的代码为你提供了两个y轴:

  library(rCharts)
  library(doBy)
  library(reshape2)
  set.seed(1)
  df <- data.frame(date=as.Date("2014-01-01")+1:10,y1=sample(1:200,70),y2=runif(70))

  buildchart <- function(df) {
  plotData<-df
  temp<-aggregate(cbind(y1)~date,data=df,min)
  tabledta<-summaryBy(y2~date,data=df,FUN=sum,keep.names = TRUE) 
  tabledta<-merge(tabledta,temp,by=c("date"),all.x=T)

  filler = expand.grid(date=seq(as.Date(min(tabledta$date)),max(as.Date(tabledta$date)),by='1 day'))
  df = merge(filler,
             tabledta,
             by=c('date'),
             all.x=T)
  df[is.na(df)]=0
  data.melt<-melt(df,id.vars=c('date'),all=TRUE)


  #Changed to 'multichart'
  p <- nPlot(value ~ date, group = 'variable', data = data.melt, type = 'multiChart')
  p$params$multi = list(
  y1 = list(type="line",yAxis=1),  y2 = list(type="line",yAxis=2))


  #The next two are commented two avoid incompatibilities
  #p$chart(margin=list(left=150))
  #p$yAxis(showMaxMin = FALSE)

  p$xAxis(tickFormat ="#!function(d) {return d3.time.format('%Y-%m-%d')(new Date(d * 24 * 60 * 60 * 1000));}!#")

  p$setTemplate(script = system.file(
  "/libraries/nvd3/layouts/multiChart.html",
  package = "rCharts"))
  p
  }

  buildchart(df)