1

当我使用guides() 规范自定义图例外观时,我发现情节中图例的交互性丢失了。

以下代码从 ggiraph 文档中的示例修改。

library(ggplot2)
library(ggiraph)

dat <- data.frame(
  name = c( "Guy", "Ginette", "David", "Cedric", "Frederic" ),
  gender = c( "Male", "Female", "Male", "Male", "Male" ),
  height = c(169, 160, 171, 172, 171 ) )
p <- ggplot(dat, aes( x = name, y = height, fill = gender,
                      data_id = name ) ) +
  geom_bar_interactive(stat = "identity")

p1 <- p +  scale_fill_manual_interactive(
  values = c(Male = "#0072B2", Female = "#009E73"),
  data_id = function(breaks) { as.character(breaks)},
  tooltip = function(breaks) { as.character(breaks)},
  onclick = function(breaks) { paste0("alert(\"", as.character(breaks), "\")") },
  labels = function(breaks) {
    lapply(breaks, function(br) {
      label_interactive(
        as.character(br),
        data_id = as.character(br),
        onclick = paste0("alert(\"", as.character(br), "\")"),
        tooltip = as.character(br)
      )
    })
  }
) + 
  guides(fill=guide_legend(title.position = "top")) +
  theme(legend.position="top")  

girafe_options(girafe(ggobj = p1),
               opts_hover_key(girafe_css("stroke:red", text="stroke:none;fill:red")))

没有guides(fill=guide_legend(title.position = "top"))线,图例将保留其交互性。

非常感谢任何帮助!

4

1 回答 1

2

而不是通过更改标题位置,guides()您可以通过以下guide参数获得所需的结果而不会失去交互性scale_fill_manual_interactive

library(ggplot2)
library(ggiraph)

dat <- data.frame(
  name = c("Guy", "Ginette", "David", "Cedric", "Frederic"),
  gender = c("Male", "Female", "Male", "Male", "Male"),
  height = c(169, 160, 171, 172, 171)
)
p <- ggplot(dat, aes(
  x = name, y = height, fill = gender,
  data_id = name
)) +
  geom_bar_interactive(stat = "identity")

p1 <- p + scale_fill_manual_interactive(
  values = c(Male = "#0072B2", Female = "#009E73"),
  data_id = function(breaks) {
    as.character(breaks)
  },
  tooltip = function(breaks) {
    as.character(breaks)
  },
  onclick = function(breaks) {
    paste0("alert(\"", as.character(breaks), "\")")
  },
  labels = function(breaks) {
    lapply(breaks, function(br) {
      label_interactive(
        as.character(br),
        data_id = as.character(br),
        onclick = paste0("alert(\"", as.character(br), "\")"),
        tooltip = as.character(br)
      )
    })
  },
  guide = guide_legend(title.position = "top")
) +
  theme(legend.position = "top")

girafe_options(
  girafe(ggobj = p1),
  opts_hover_key(girafe_css("stroke:red", text = "stroke:none;fill:red"))
)

在此处输入图像描述

于 2021-11-14T23:37:33.817 回答