Plotly:使用for循环添加跟踪时会覆盖文本

时间:2017-09-19 14:50:42

标签: r loops plotly

我创建了一个绘图散点图,我使用for循环添加了痕迹。当我添加文本标签或hoverinfo时,最后一个点的文本会覆盖所有其他文本。有谁知道如何防止这种情况?

我在下面创建了一个可重复的示例,其中在循环外创建(正确命名的)蓝点,但是在循环内创建的红点的名称被覆盖(所有错误标记为E而不是A-> E):

library(plotly)

data.frame1 <- data.frame("name"=paste("name", LETTERS[6:10]), "x"=-1:-5, "y"=-1:-5)
data.frame2 <- data.frame("name"=paste("name", LETTERS[1:5]), "x"=1:5, "y"=1:5)


p <- plot_ly(data.frame1, x = ~x, y = ~y, text = ~paste0(name), 
                         name = "Outside loop", type ="scatter", 
                         mode = "markers+text", marker=list(color="blue") ) 


for(i in 1:nrow(data.frame2)) {
    point <- data.frame2[i, ]
    p <- p %>% add_trace(x = point$x, y = point$y,  text = ~paste0(point$name), 
                                             type ="scatter", mode = "markers+text",
                                             marker = list(color="red", size=10), 
                                             name=point$name )

}

p

enter image description here

1 个答案:

答案 0 :(得分:1)

~符号导致问题,在循环中删除它应该没问题。当您像第一个示例中那样引用数据框时它是有意义的,但它会导致您在循环中观察到的奇怪行为。

enter image description here

library(plotly)

data.frame1 <- data.frame("name"=paste("name", LETTERS[6:10]), "x"=-1:-5, "y"=-1:-5)
data.frame2 <- data.frame("name"=paste("name", LETTERS[1:5]), "x"=1:5, "y"=1:5)


p <- plot_ly(data.frame1, x = ~x, y = ~y, text = ~paste0(name), 
             name = "Outside loop", type ="scatter", 
             mode = "markers+text", marker=list(color="blue") ) 

for(i in 1:nrow(data.frame2)) {
  point <- data.frame2[i, ]
  print(paste0(point$name))
  p <- p %>% add_trace(x = point$x, y = point$y,  text = paste0(point$name), 
                       type ="scatter", mode = "markers+text",
                       marker = list(color="red", size=10), 
                       name=point$name )

}

p