使用曲线R在双轴图表上工作时,跟踪不正常

时间:2018-01-24 05:28:01

标签: r plotly r-plotly

我已经在下面写了一段代码,用于在R中使用plotly绘制双轴图表。

代码:

## Date creation
dtMasterWithtotals <- data.table("Period_Month" = c('7/1/2017', '9/1/2017'), A = c(171, 448), B = c(0, 655), C = c(476, 812))

## Vectors to select categories for primary and secondary axis
vecPrimaryAxis <- c("A", "B") 
vecSecondaryAxis <- c("C")

## X-axis properties
ax <- list(
  type = "category",
  categoryorder = "array",
  categoryarray = dtMasterWithtotals[order(as.Date(dtMasterWithtotals[, Period_Month])),], 
  showgrid = TRUE,
  showline = TRUE,
  autorange = TRUE,
  showticklabels = TRUE,
  ticks = "outside",
  tickangle = 0
)


## arrange columns in an order – TBD
## The plot function below assumes that the data will be in format, Period_Month, A, B,C.

## Plot function
plot <- plot_ly(dtMasterWithtotals, x = ~Period_Month, y = dtMasterWithtotals[[2]], type = "scatter", mode = 'lines', name = names(dtMasterWithtotals)[2])

if(length(vecPrimaryAxis) > 1){
  t <- (3 + length(vecPrimaryAxis) - 2)
  for (i in 3:t){
    plot <- add_trace(plot, x = ~Period_Month, y = dtMasterWithtotals[[i]], type = "scatter", mode = "lines", name = names(dtMasterWithtotals)[i]) %>%
      layout(xaxis  = ax)
  }
}

if(length(vecSecondaryAxis) > 0){
  p <- 2 + length(vecPrimaryAxis)
  q <- p + length(vecSecondaryAxis) - 1
  for (j in (p:q)){
    plot <- add_trace(plot, x = ~Period_Month, y = dtMasterWithtotals[[j]], type = "scatter", mode = "lines", yaxis = "y2", name = names(dtMasterWithtotals)[j]) %>%
      layout(yaxis2 = list(overlaying = "y", side = "right"), xaxis = ax)
  }
}

当尝试在主y轴上绘制A和B并在辅助y轴上绘制C时,最后一条迹线(在本例中为C)与第二条迹线(在本例中为B)重叠,产生两条迹线而不是三条迹线。但是,在悬停时,新迹线会显示正确的值标签,但在可视化中出现错误(位置错误)。

如果您需要任何其他细节,请与我们联系。

感谢。

1 个答案:

答案 0 :(得分:1)

如果我理解你想要的东西,事实上,你的代码没有问题。您只需手动设置y和y2轴。为了更容易可视化,我简单地颠倒了y2轴。如果你试试这个:

plot_ly() %>%
    add_lines(data=dtMasterWithtotals, x = ~Period_Month, y = ~A, name = "A") %>%
    add_lines(data=dtMasterWithtotals, x = ~Period_Month, y = ~B, name = "B") %>%
    add_lines(data=dtMasterWithtotals, x = ~Period_Month, y = ~C, name = "C", yaxis = "y2") %>%
    layout(xaxis  = ax, yaxis2 = list(overlaying = "y", side = "right", autorange="reversed"))

它会给你这个:

enter image description here

如您所见,所有三条线都是可见的,并且所有三条线都显示正确的值。