10

I would like to put my legend inside the plot as answered in this question, but for an interactive plot.

In the first code chunk the legend disappears off the plot, but when I remove the interaction it works.

library(ggvis)
library(dplyr)

# With drop down list it doesn't work
mtcars %>% 
  ggvis(x = ~wt, y = input_select(c("Miles per gallon" = "mpg", "Horse power" = "hp", "Displacement"="disp", "Carbohydrates" = "carb"), map = as.name, selected = "mpg", label = "Variables"), fill=~cyl) %>% 
  layer_points() %>% 
  add_relative_scales() %>%
  add_legend("fill", title = "Cylinders",
             properties = legend_props(
               legend = list(
                 x = scaled_value("x_rel", 0.8),
                 y = scaled_value("y_rel", 1)
               )))

enter image description here

# Remove interaction and it works
mtcars %>% 
  ggvis(x = ~wt, y = ~mpg, fill = ~cyl) %>% 
  layer_points() %>% 
  add_relative_scales() %>%
  add_legend("fill", title = "Cylinders",
             properties = legend_props(
               legend = list(
                 x = scaled_value("x_rel", 0.8),
                 y = scaled_value("y_rel", 1)
               )))

enter image description here

How can I overlay the legend in an interactive plot?

Community
  • 1
  • 1
Tom
  • 4,860
  • 7
  • 43
  • 55
  • 1
    With your first chunk of code, when I chose `Horse power`, the legend appeared. But it disappeared when I chose `Miles per gallon`. Since the value of y axis changes depending on users' choices, I wonder if there is something to do with this y-lim change. I somehow think that the legend position is set with the largest y value. `Horse power` has more than 300 whereas `Miles per gallon` has only 34. So by the time one chooses the latter, the legend disappears... This is just my speculation. – jazzurro Oct 20 '15 at 13:32
  • @jazzurro Interesting! Thank you for your speculation. Although, it seems to be arbitrarily every other selection. I added two more options to the drop down, If you choose `Horse power` and then choose `Displacement` and then choose `Miles per gallon` it appears. – Tom Oct 20 '15 at 23:54
  • This seems pretty buggy to me. I wonder if this issue is filed on github. It may be worth reporting this case. – jazzurro Oct 21 '15 at 00:07

1 Answers1

2

It seems this is an open issue. Brief workaround I've found on https://github.com/rstudio/ggvis/issues/347 : add

%>% set_options(duration=0)

to the end of the plot:

mtcars %>% 
  ggvis(x = ~wt, y = ~mpg, fill = ~cyl) %>% 
  layer_points() %>% 
  add_relative_scales() %>%
  add_legend("fill", title = "Cylinders",
         properties = legend_props(
           legend = list(
             x = scaled_value("x_rel", 0.8),
             y = scaled_value("y_rel", 1)
           ))) %>% set_options(duration=0)

It doesn't redraw the legend and that therefore doesn't disappear.

JaKu
  • 1,096
  • 16
  • 29