簡體   English   中英

R plotly 在跟蹤循環中懸停文本的問題

[英]R plotly Issues with hovering text in a trace loop

這篇文章這個答案之后,我還有一個問題:

library(plotly)      

# Create data
dat=data.frame(group = factor(rep(LETTERS[1:4], each=10)), my_x = rep(1:10, 4), my_y = rnorm(40))
str(dat)

# Let's do a first plot
p<-plot_ly(dat)


# Add a trace for each group using a loop

for(i in 1:length(levels(dat$group))){

subs <- subset(dat, group == levels(dat$group)[i])

p<-add_trace(p = p,
             data = subs,
             y=~my_y, 
             x=~my_x , 
             name=levels(dat$group)[i],
             type="scatter", 
             mode="markers+lines",
             hoverinfo="text",
             text=~paste0(levels(dat$group)[i], ": x=", round(my_x, 2), "y=", round(my_y, 2)))

}

p

誰能告訴我為什么當我將鼠標懸停在數據點上時,每個標簽都顯示正確的 x 和 y 值,但是,它們都被標記為“D:”,而圖例顯示的線條類似於 A、B , C & D. 我希望正確標記懸停文本。

text使用~可能是一個問題。 嘗試分別使用“subs”數據創建“text”,然后將其傳遞給add_trace

 p <- plot_ly()
 lvls <- levels(dat$group)
 for(i in seq_along(lvls)){
   subs <- droplevels(subset(dat, group == lvls[i]))
   text1 <- with(subs, paste0(lvls[i], ": x=", round(my_x, 2), "y=", round(my_y, 2)))
   p <- add_trace(p, 
                  data = subs,
                  x = ~my_x, 
                  y = ~my_y,
                  name = lvls[i],                  
                  type = 'scatter', 
                  mode = 'markers+lines', 
                  hoverinfo='text',
                  text=text1)
 }

 p

-輸出在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM