R语言 是否可以在创建绘图后修改ggplotly的悬停文本?

yks3o0rb  于 2023-10-13  发布在  其他
关注(0)|答案(1)|浏览(116)

让我们想象一下,我有三个农场的数据,它们生产的水果,蔬菜和浆果的比例不同。我想把所有的这些都比较一下,然后做一个很酷的维恩图。然而,我也希望纳入数据,说明哪些类型的产品是每两个农场或所有农场共有的。最好的办法是制作一个plotly小部件,显示有多少组是共同的,而不是显示文本,显然列出了用于放置文本的数据点(见图片)。问:是否有可能修改ggplotly对象创建后实现此行为?理想情况下,我希望在深灰色框中看到“蔬菜,浆果”(因为这些是B和C之间共享的植物群),而不是现在显示的任何东西。
代码:

library(ggvenn)
library(plotly)
# Fruits
fruits <- c("Apple", "Banana", "Orange", "Mango", "Pineapple", "Peach", "Pear", "Grapefruit", "Lemon", "Kiwi")

# Vegetables
vegetables <- c("Carrot", "Broccoli", "Cauliflower", "Spinach", "Kale", "Potato", "Onion", "Garlic", "Cucumber", "Tomato")

# Berries
berries <- c("Strawberry", "Blueberry", "Raspberry", "Blackberry", "Cranberry", "Gooseberry", "Elderberry", "Mulberry", "Boysenberry", "Currant")

fvb <- c(fruits, vegetables, berries)
set.seed(344)
vennda <- list("A" = sample(fvb, 10),
     "B" = sample(fvb, 10),
     "C" = sample(fvb, 10))

gg <- ggvenn(vennda)
ggp <- ggplotly(gg)
ggp

结果plotly图片:

bgtovc5b

bgtovc5b1#

嗯,我发现你可以很容易地访问悬停文本标签。剩下的就是弄清楚如何准备这些,所以这里是我的答案,这似乎有效

all_items <- c(fruits, vegetables, berries)
all_categories <- c(rep("Fruits", length(fruits)), rep("Vegetables", length(vegetables)), rep("Berries", length(berries)))
item_to_category <- setNames(all_categories, all_items)
#sub-function for generating correct intersections
find_unique_elements <- function(lst) {
  lapply(seq_along(lst), function(i) {
    current_set <- lst[[i]]
    other_sets <- do.call(c, lst[-i])
    setdiff(current_set, other_sets)
  })
}
# Function to calculate all intersections
calculate_intersections <- function(sets) {
  n <- length(sets)
  combs <- lapply(1:n, function(i) combn(1:n, i, simplify = FALSE))
  intersections <- lapply(combs, function(comb_set) {
    lapply(comb_set, function(indices) {
      Reduce(intersect, sets[indices])
    }) %>% find_unique_elements()
  })
  return(do.call(c, intersections))
}

# Function to generate hover texts
generate_hover_texts <- function(intersections, item_to_category) {
  lapply(intersections, function(intersect_set) {
    categories <- unique(item_to_category[intersect_set])
    paste(categories, collapse = ", ")
  })
}

# Calculate all intersections
all_intersections <- calculate_intersections(vennda)

# Generate hover texts
hover_texts <- generate_hover_texts(all_intersections, item_to_category)

# Hoverlabels are stored in ggp$x$data[[6]]$hovertext, so let's update hover texts in the Plotly object
ggp$x$data[[6]]$hovertext <- hover_texts
ggp

相关问题