When I used guides() specifications to customise legend appearance, I found that the interactive nature of the legend in the plot is lost.
The following code modified from the example in the ggiraph documentation.
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")))
Without the guides(fill=guide_legend(title.position = "top"))
line, the legend retains its interactivity.
Any help is highly appreciated!
Instead of changing the title position via guides()
you could achieve your desired result without losing the interactivity via the guide
argument of 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"))
)