R Plotly 在等高线图上显示字符串

R Plotly show string on contour plots

我叠加了两个等高线图:

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
                       ))

能不能有这样的剧情:

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

您一直在寻找的是 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
  )

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