在使用type =“ scatter”时,Plotly忽略了我设置的配色方案,但是在使用type = NULL时,它保留了它,即使在代码后面没有设置配色方案也是如此。
尝试使用mode =“ markers”或mode =“ lines”或mode =“ lines + markers”会导致创建多行。
对于该代码示例,我意识到mtcars是一个奇怪的数据集,可向其中添加警报和时间,但它确实显示了问题。我已经修复了代码,并且在生产中使用type = NULL,但是可以推测出绘图类型似乎不稳定(并且在某些情况下,它假定为条形图)。
如果我在第1节中使用type = NULL,那么我会得到正确的配色方案(红色,黄色,绿色)。
如果我使用type =“ scatter”,那么它将使用不同的配色方案。 如果我使用type =“ scatter”,mode =“ lines + markers”,它也会使用不同的配色方案。
当x轴为正数或日期时,则至少将其全部保留为一条带有不同色点的线。但是由于我依靠type = NULL来获取正确的配色方案(取决于时间组件的类别),因此它可能会采用条形图,或创建多行(每条警报一条)。
library(plotly)
pal <- c("red","yellow","green4")
pal <- setNames(pal,c("Serious","Moderate","Low"))
x = NULL
for(i in 2007:2009){
for(j in 1:12)
x <- c(x, paste(i,j,"01",sep="-"))
}
x <- x[1:nrow(mtcars)]
x <-as.Date(x)
y <- as.POSIXct(x)
set.seed(4)
mtcars$alert <- sample(c("Serious","Moderate","Low"),size =
nrow(mtcars),replace = TRUE)
mtcars$date <- x
mtcars$posixct <- y
#' Section 1
p <- plot_ly(mtcars, width = 800,
height = 600, type = NULL # must be made null
#' for some reason using any other type (i.e. scatter)
#' results in multiple traces for each factor (i.e. when you color
#' by the alert, multiple lines are created.) OR results in the colors being ignored
#' The only current workaround is for plot_ly to assume scatter
#' in which case it does not separate the values into new traces and keeps the set colors.
#' in ggplot you can use geom_point() and geom_line() to layer the
#' graphics, but this is not possible in plot_ly.
) %>%
#' Section 2
add_markers(x=~posixct, y=~wt, mode = "markers",color =~alert, colors = pal,
marker =list(size = 10)) %>%
add_trace(x=~posixct,y=~wt,mode = 'line',
line = list(color = 'rgb(0, 0, 0)', width = 2), showlegend=FALSE)
p <- p %>% layout(
xaxis = list(title = "Time"),
yaxis = list(title = "weight"),
title = "weight over index as a time", titlefont = list(size = 20),
margin = list(l = 50, r = 50, t = 50, b = 50),
showlegend = TRUE,legend = list(traceorder = "reversed")
)
config(p,collaborate = FALSE,cloud = FALSE,displaylogo = FALSE,
modeBarButtonsToRemove = c("zoom2d","pan2d","select2d","lasso2d",
"zoomIn2d","zoomOut2d","autoScale2d",
"hoverCompareCartesian","toggleHover","toggleSpikelines"))