【问题标题】:Viewing hover info for overlapping scatter points in Plotly R在 Plotly R 中查看重叠散点的悬停信息
【发布时间】:2019-03-20 00:19:45
【问题描述】:

我很惊讶我无法用谷歌搜索这个解决方案,所以我想我会发布一个帖子。当然其他人也有同样的问题......

我遇到的问题是,当两个或多个散点重叠时(即相同的 x 和 y),悬停信息仅显示顶点的信息。

例子:

df <- data.frame(ID=1:6, x=c(5:9, 7), y=c(1:5, 3)+10, info=paste('Hover information: ',c(LETTERS[c(1:6)])))
df                 

plot_ly(df) %>% 
  add_trace(x = ~x, 
            y = ~y, 
            type = 'scatter', 
            mode = 'markers', 
            marker = list(color   = 1:6, 
                          symbol  = 1:6, 
                          size    = 25),
            hoverinfo = "text",
            text = df$info)

是否可以同时显示中间点的 hoverinfo?可能是:

Hover information: C
Hover information: F

【问题讨论】:

    标签: r plotly


    【解决方案1】:

    您可以尝试使用 add_markers() 和 jitter,例如:

    plot_ly(df) %>% 
      add_markers(x = ~jitter(x, 1), 
                  y = ~jitter(y, 1), 
                  type = 'scatter', 
                  mode = 'markers', 
                  marker = list(color   = 1:6, 
                                symbol  = 1:6, 
                                size    = 25),
                  hoverinfo = "text",
                  text =  ~info)
    

    但是要获得您设计的多个信息,也许您需要修改您的数据框(但您会丢失颜色代码):

    df$info <- as.character(df$info)
    
    df$combined_info[1] <- df$info[1]
    
    for(i in 2:nrow(df)){
      df$combined_info[i] <- df$info[i]
    
      for(j in 2:i-1){
        if((df$x[j] == df$x[i]) && (df$y[j] == df$y[i])){
          df$combined_info[i] <- paste0(df$combined_info[j], "<br>",
                                        df$info[i])
        }
      }
    }
    

    然后你可以使用原来的情节代码,同时改变“文本”参数:

    plot_ly(df) %>% 
      add_trace(x = ~x, 
        ...
        text =  ~combined_info)
    

    【讨论】:

    • 感谢您的建议!应用抖动对我来说是不可能的,但你不知道!您的第二个选择是前进的好方法!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2016-07-12
    • 2016-12-21
    • 1970-01-01
    • 2019-05-29
    • 2022-01-02
    • 2020-12-18
    • 2019-08-13
    • 2022-09-25
    相关资源
    最近更新 更多