This works fine
library(dplyr)
library(ggvis)
years <- as.factor(c(2013,2013,2014,2014,2015,2015))
months <- c(1,2,1,2,1,2)
values <- c(3,2,4,6,5,1)
df <- data.frame(years,months,values)
df %>%
group_by(years) %>%
ggvis(~months, ~values) %>%
layer_points( fill = ~years)
However, when I add a tooltip the points all appear momentarily but only the 2015 values remain
df <- cbind(df, id = seq_len(nrow(df)))
all_values <- function(x) {
if(is.null(x)) return(NULL)
row <- df[df$id == x$id,]
paste0(names(row),": ",format(row), collapse = "<br />")
}
df %>%
group_by(years) %>%
ggvis(~months, ~values, key:= ~id) %>%
layer_points( fill = ~years) %>%
add_tooltip(all_values, "hover")
Probably some simple error, but any help appreciated cheers
The problem lies in you putting
group_by
before ggvis and callingadd_tooltip
afterwards. Just putgroup_by
part after ggvis callno idea why it happens though
At the moment, trying to add a tooltip specific to a row when the data are grouped doesn't seem to work. This makes some sense, actually, as the grouping implies that you may want info by group.
You don't need grouping in your
layer_points
example at all, but you would need it if you wanted lines between the points for specific years as well as points. If this is what you wanted, you'd group the dataset after you add the points, and putkey
inlayer_points
instead of in the overallggvis
.This isn't totally ideal, because the tooltip still shows up for the lines even though lines don't have unique id data associated with them. To change this, make a small change to your tooltip function to check just if the id variable is
NULL
rather than the whole dataset fromggvis
.You can add a tooltip at the group level, but you'll need to figure out what sort of summary info you want to display. In the function for the tooltip you will be working with the grouping variable instead of
id
.For example, you could just show all values associated with the group. The way I've set this up you'll need to click on the line to see the group info:
You may want to show summary information, instead. In this example, I'll display the overall change in
values
and how many months passed in the tooltip. I make the summary dataset with functions from dplyr.