3

I'm generating a graph with ggvis and the legends are in top of each-other.

library(ggvis)
df1 <- data.frame(x=c(0.6,1,1.4), y=c(-2, -.8, -0.2), number=c(10,8,6), 
                  type=c('A', 'A', 'B'))
df1 %>% ggvis(x = ~x, y = ~y) %>% 
  layer_points(shape=~type, fill=~number) 

enter image description here

How can I fix this?

Thanks!


Steven's solution works for the simple example but It does not work when you add a tooltip:

library(ggvis)
df1 <- data.frame(x=c(0.6,1,1.4), y=c(-2, -.8, -0.2), number=c(10,8,6), 
                  type=c('A', 'A', 'B'), id=c(1:3))

tooltip <- function(x) {
  if(is.null(x)) return(NULL)
  row <- df1[df1$id == x$id, ]
  paste0(names(row), ": ", format(row), collapse = "<br />")
}

df1 %>% ggvis(x = ~x, y = ~y) %>% 
  layer_points(shape=~type, fill=~number, key := ~id)  %>% 
  add_tooltip(tooltip, "hover") %>%
  add_legend("shape", properties = legend_props(legend = list(y = 50)))
Ignacio
  • 7,646
  • 16
  • 60
  • 113

1 Answers1

3

Try:

df1 %>% ggvis(x = ~x, y = ~y) %>% 
  layer_points(shape=~type, fill=~number) %>%
  add_legend("shape", properties = legend_props(legend = list(y = 50)))

enter image description here


Edit:

As mentionned by @aosmith, you could use the set_options() workaround:

df1 %>% ggvis(x = ~x, y = ~y) %>% 
  layer_points(shape=~type, fill=~number, key := ~id)  %>% 
  add_tooltip(tooltip, "hover") %>%
  add_legend("shape", properties = legend_props(legend = list(y = 50))) %>%
  set_options(duration = 0)
Steven Beaupré
  • 21,343
  • 7
  • 57
  • 77
  • This solution does not work when you have a tooltip :( I just added that example. Thanks! – Ignacio Jun 18 '15 at 13:54
  • 1
    @Ignacio Adding `set_options(duration = 0)` to the end of the pipe might help with the addition of the tooltip. See the conversation at [github issue #125](https://github.com/rstudio/ggvis/issues/125). – aosmith Jun 18 '15 at 14:29
  • 1
    @aosmith I was actually reading the same issue when you posted your comment. Still early days for `ggvis` ;) – Steven Beaupré Jun 18 '15 at 14:35