I try to reorder drv
and class
in mpg
data, and then plot the boxplots of hwy
with those two character variables as fill
argument in aes
of the ggplot
. I use giraffe
for that. But when I put the graphs together the hover effect not works properly. I want the plots to be synced in a way that hovering mouse in one of them results in same color effect.
library(tidyverse)
library(ggiraph)
library(patchwork)
g1 <- mpg %>%
mutate(drv = (fct_reorder(drv, hwy))) %>%
ggplot(aes(x = hwy, y = drv, fill = drv, data_id = drv)) +
geom_boxplot_interactive() +
theme(legend.position = 'none')
g2 <- mpg %>%
mutate(class = (fct_reorder(class , hwy))) %>%
ggplot(aes(x = hwy, y = class , fill = drv, data_id = drv)) +
geom_boxplot_interactive() +
theme(legend.position = 'none')
girafe(
ggobj = g1 + plot_spacer() + g2 + plot_layout(widths = c(0.45, 0.1, 0.45)),
options = list(
opts_hover(css = ''),
opts_hover_inv(css = "opacity:0.1;"),
opts_sizing(rescale = FALSE)
),
height_svg = 5,
width_svg = 9
)
The issue is that you reordered drv
for the first plot, i.e. it is a factor
. Hence you get a different assignment of the fill colors and more importantly linking the two plots by drv
will no longer work. The reason is that for a factor
the numeric representation is stored in the data_id
column, whereas the data_id
for the second plot contain the original character
values. As a consequence there are no matching data_id
s.
To fix that you could use a helper drv
column for the first plot to perform the reordering and which could be mapped on y
while for the fill
and the data_id
you use the original drv
column:
library(tidyverse)
library(ggiraph)
library(patchwork)
g1 <- mpg %>%
mutate(drv1 = fct_reorder(drv, hwy)) %>%
ggplot(aes(x = hwy, y = drv1, fill = drv, data_id = drv)) +
geom_boxplot_interactive()
g2 <- mpg %>%
mutate(class = fct_reorder(class, hwy)) %>%
ggplot(aes(x = hwy, y = class, fill = drv, data_id = drv)) +
geom_boxplot_interactive()
p <- g1 + plot_spacer() + g2 +
plot_layout(widths = c(0.45, 0.1, 0.45)) &
theme(legend.position = "none")
girafe(
ggobj = p,
options = list(
opts_hover(css = ""),
opts_hover_inv(css = "opacity:0.1;"),
opts_sizing(rescale = FALSE)
),
height_svg = 5,
width_svg = 9
)