【问题标题】:R Plotly show string on contour plotsR Plotly在等高线图上显示字符串
【发布时间】:2020-05-13 16:33:11
【问题描述】:

我已经叠加了两个等高线图:

library(plotly)
cluster_count <- 5
volcan <- plot_ly(z = ~volcano, 
                  type = "contour",
                  contours = list(
                    coloring= "fill",
                    showlines = F
                  ))
cluster_matrix <- volcano
cluster_matrix[cluster_matrix < 100] <- 1
cluster_matrix[cluster_matrix <= 120 & cluster_matrix >= 100] <- 2
cluster_matrix[cluster_matrix < 140 & cluster_matrix >= 120] <- 3
cluster_matrix[cluster_matrix <= 160 & cluster_matrix >= 140] <- 4
cluster_matrix[cluster_matrix > 160] <- 5

cluster_name_matrix <- cluster_matrix
cluster_name_matrix[cluster_matrix ==1] <- "Eins"
cluster_name_matrix[cluster_matrix ==2]  <- "Zwei"
cluster_name_matrix[cluster_matrix ==3]  <- "Drei"
cluster_name_matrix[cluster_matrix ==4]  <- "Vier"
cluster_name_matrix[cluster_matrix ==5]  <- "Funf"

volcan %>% add_contour(cluster_matrix, 
                       type = "contour", 
                       opacity =1,
                       text=cluster_name_matrix,
                       hovertemplate = 'Cluster: %{text}<extra></extra>',
                       autocontour = F,
                       line=list(color="orange"),
                       contours = list(
                         start = 1,
                         showlabels = T,
                         coloring= "lines",
                         end = cluster_count,
                         size = 1,
                         showlines = T
                       ))

有没有可能有这样的情节:

就像我对悬停文本所做的那样?提前感谢您的提示和建议!

【问题讨论】:

    标签: r plotly r-plotly


    【解决方案1】:

    您一直在寻找的是add_annotations() 函数。在下面的代码中,我编写了一个函数,它为每个级别检索一个随机坐标对,然后将相应的坐标传递给add_annotations() 函数。请注意,我将您的等高线图存储在变量 p 中:

    library(purrr)
    
    # Custom function
    find_rand_annotation_index <- function(name_matrix, string){
      d <- which(name_matrix == string, arr.ind = TRUE)
      d2 <- as.data.frame(d[sample(nrow(d), size = 1), , drop = FALSE])
      cbind(d2, string)
    }
    
    # Get 5 random coordinates to plot the labels
    text_coords <- purrr::map_dfr(c("Eins", "Zwei", "Drei", "Vier", "Funf"), ~ find_rand_annotation_index(cluster_name_matrix, .x))
    
    # Plot the annotations on the contour plot
    p %>%
      add_annotations(
        x = text_coords$col,
        y = text_coords$row,
        text = text_coords$string,
        font = list(color = "IndianRed"),
        showarrow = F
      )
    

    标签的位置可能不符合您的喜好(因为坐标是随机选择的),但您可能希望在代码中对其进行一些处理。

    【讨论】:

      猜你喜欢
      • 2021-11-30
      • 2018-11-19
      • 2018-08-31
      • 2019-08-05
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多