Disappearing values in ggvis when using tooltip on grouped data - r

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

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 put key in layer_points instead of in the overall ggvis.
df %>%
ggvis(~months, ~values) %>%
layer_points( fill = ~years, key:= ~id) %>%
add_tooltip(all_values, "hover") %>%
group_by(years) %>%
layer_lines(stroke = ~years, strokeWidth := 2)
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 from ggvis.
all_values = function(x) {
if(is.null(x$id)) return(NULL)
row <- df[df$id == x$id,]
paste0(names(row),": ",format(row), collapse = "<br />")
}
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:
group_values1 = function(x) {
if(is.null(x)) return(NULL)
group = df[df$years == unique(x$years),]
paste0(names(group), ": ", format(group), collapse = "<br />")
}
df %>%
ggvis(~months, ~values) %>%
layer_points( fill = ~years, key:= ~id) %>%
add_tooltip(all_values, "hover") %>%
group_by(years) %>%
layer_lines(stroke = ~years, strokeWidth := 2) %>%
add_tooltip(group_values1, "click")
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.
group_values2 = function(x) {
if(is.null(x)) return(NULL)
group = df[df$years == unique(x$years),]
groupval = group %>% group_by(years) %>%
summarise(`Change in value` = max(values) - min(values),
`Months Passed` = max(months) - min(months))
paste0(names(groupval), ": ", format(groupval), collapse = "<br />")
}
df %>%
ggvis(~months, ~values) %>%
layer_points( fill = ~years, key:= ~id) %>%
add_tooltip(all_values, "hover") %>%
group_by(years) %>%
layer_lines(stroke = ~years, strokeWidth := 2) %>%
add_tooltip(group_values2, "click")

The problem lies in you putting group_by before ggvis and calling add_tooltip afterwards. Just put group_by part after ggvis call
df %>%
ggvis(~months, ~values, key:= ~id) %>%
group_by(years) %>%
layer_points( fill = ~years) %>%
add_tooltip(all_values, "hover")
no idea why it happens though

Related

What is a good approach to add sparkline chart to an R gt table

I am trying to use R sparkline with gt. My question is very similar to this one Is it possible to use sparkline with gt?, but on top of simply using sparkline with gt as in the referenced question, I am trying to use it as part of the summary row. Below is the picture of what I have achieved so far. Here are my two questions:
How can I remove the two grey lines that are printed as part of the sparkline chart in the summary row?
Is there a better way to add sparkline to the summary row of a gt table?
library(tidyverse)
library(sparkline)
library(gt)
# toy data
df <- tibble(
name = rep(c("A", "B"), each = 20),
value = runif(40, min = -10, max = 10) %>% cumsum()
) %>%
group_by(name) %>%
mutate(
index = row_number()
) %>% ungroup()
# preparing the data for the standard sparkline
regular_sparkline_df <- df %>%
group_by(name) %>%
summarise(
chart = spk_chr(
value,
type="line"
)
)
# here I try to prepare the data for the summary row by getting the whole gt table and then removing the header
summary_row_sparkline_df <- df %>%
group_by(index) %>%
summarise(value = sum(value)) %>% ungroup() %>%
summarise(
chart = spk_chr(
value,
type="line"
)
) %>%
gt() %>%
fmt_markdown(columns = vars(chart)) %>%
gt:::as.tags.gt_tbl() %>%
htmltools::attachDependencies(htmlwidgets::getDependency("sparkline")) %>%
as.character() %>%
gsub('<thead.+</thead>', "", .) # removing the header of the table
# building the html and adding dependencies
p_html <- regular_sparkline_df %>%
gt() %>%
fmt_markdown(columns = vars(chart)) %>%
grand_summary_rows(
columns = "chart",
fns = list(Total = ~as.character(summary_row_sparkline_df)),
formatter = fmt_markdown
) %>%
gt:::as.tags.gt_tbl() %>%
htmltools::attachDependencies(htmlwidgets::getDependency("sparkline"))
# seeing the table in the RStudio
print(p_html, browse = interactive())

Multiple line graphs in ggvis using for loop

I am trying to create multiple line graphs using ggvis. I am able to plot multiple lines but I am unable to add tooltip for these lines. I need to show the x and y value when I hover the mouse on the lines. I also am unable to add points to the lines in the for loop.
Below is a simplified example I am working with. column "c1" is the x values and columns "c2", "c3" and "c4" are to be plotted(lines with points and tooltip)
Screenshot of the plot
mydf <- data.frame(c(1:10),c(11:20), c(21:30), c(31:40))
v <- c("c1","c2","c3", "c4")
names(mydf) <- v
myggv <- mydf %>% ggvis(x = ~c1, y = ~c2) %>% layer_lines() %>% layer_points() %>% add_tooltip( function(mydf){paste0("x:",mydf$c1,"<br>","y:",mydf$c2)}, "hover")
for(r in v[2:length(v)]){
myggv <- (myggv %>% layer_paths(x = ~c1, y = as.name(r)) %>% layer_points()
%>% add_tooltip( function(mydf){paste0("x:",mydf$c1,"<br>","y:",mydf[,r] )}, "hover"))
}
Thanks
The best approach here is to not use a for loop. I mean, you can, but it's not the way ggvis approaches things. Also I can't get the tooltip to work in the loop (it gives the only the correct result for the last added line. But here is how I would do it anway:
mydf <- data.frame(c1 = c(1:10),
c2 = c(11:20),
c3 = c(21:30),
c4 = c(31:40))
myggv <- ggvis(mydf)
for (r in names(mydf)[-1]) {
myggv <- (myggv %>%
layer_paths(x = ~c1, y = as.name(r)) %>%
layer_points(x = ~c1, y = as.name(r)) %>%
add_tooltip(function(mydf) {
paste0("x:", mydf[[1]], "<br>", "y:", mydf[[r]])}, "hover"))
}
The nicer way is to restructure your data, and then use group_by to create seperate lines. As an added benefit, this is perhaps nicer to read. This way your tooltips also work:
mydf2 <- tidyr::gather(mydf, 'var', 'val', -c1)
myggv2 <- mydf2 %>%
ggvis(x = ~c1, y = ~val) %>%
layer_points() %>%
add_tooltip(function(d) { paste0("x:", d$c1, "<br>", "y:", d$val) }, "hover") %>%
group_by(var) %>%
layer_paths()
You might want to use layer_lines() instead of layer_paths().

Even Axis in R Charts

I've searched a bit, but I'm not able to find a way to acheive my axis goals. There are really 2 questions here.
How can I guarantee the spacing between my major ticks is the same? If it means some dots overlap, then so be it.
Is there a way to add a zoom/date range control to this chart? Data goes from 2013 to current and is continually added.
2.b. If I do this, is there a way to have it as you zoom out it automatically start bucketing by week, then month, then year? and of course the inverse.
Here is where you can get the data: https://opendata.miamidade.gov/311/311-Service-Requests-Miami-Dade-County/dj6j-qg5t
Here is the image of the current chart:
Note that I am doing this to learn R, and hence any erraneous suggestions are also appreciated. Here is the code that generates this:
#Graphics Visualizations Package
library("ggvis")
#Adds %>% forward pipe operator
library("magrittr")
#adds grouping and manipulations
library("dplyr")
#adds data fiendlyness stuffs
library("tidyr")
library("shiny")
library("checkpoint")
checkpoint("2016-03-29")
rData <- read.csv("C:\\data\\Miami_311.csv",
header=TRUE,
sep=",")
rDSamp <- rData[sample(1:length(rData$Case.Owner), 1000),]
#Convert to known date time
rDSamp$Ticket.Created.Date...Time <-
rDSamp$Ticket.Created.Date...Time %>%
as.POSIXct(format="%m/%d/%Y") %>%
as.character()
FilterDateRange = function(data, feature, minDate, maxDate) {
minDate = minDate %>%
as.POSIXct(format="%m/%d/%Y") %>%
as.character()
maxDate = maxDate %>%
as.POSIXct(format="%m/%d/%Y") %>%
as.character()
result = subset(data, data[feature] <= maxDate)
subset(result, result[feature] >= minDate)
}
d <- rDSamp %>%
FilterDateRange("Ticket.Created.Date...Time", "1/1/2013", "12/31/2013") %>%
group_by(Ticket.Created.Date...Time, Case.Owner) %>%
summarise(
count = n()
) %>%
arrange(Ticket.Created.Date...Time)
xAxisValues = "1/1/2013" %>%
as.Date(format="%m/%d/%Y") %>%
as.character() %>%
as.Date() %>%
seq(by = "1 months", length.out = 12)
d %>%
ggvis(~Ticket.Created.Date...Time, ~count) %>%
layer_points(fill = ~Case.Owner) %>%
add_tooltip(function(data){
paste("Owner:", data$Case.Owner, "<br>","Date:", data$Ticket.Created.Date...Time)
}, "hover") %>%
add_axis("x",
title = "Date",
values = xAxisValues,
ticks = 365,
properties = axis_props(
majorTicks = list(strokeWidth = 2)))

R ggvis font and parameters of interactive text in scatter plot (hover)

I would like to know if there is a way to modify the characteristics of the text shown on "hover" using ggvis.
I have created a scatter plot based on a template found on internet and modified for my needs.
The script follows:
library(shiny)
library(ggvis)
mydata <- data
mydata$id <- 1:nrow(mydata) # Add an id column to use ask the key
all_values <- function(x) {
if(is.null(x)) return(NULL)
row <- mydata[mydata$id == x$id, ]
paste0(
names(row), ": ", format(row), collapse = "\n"
)
}
# factor Location
mydata %>% ggvis(~a, ~b, key := ~id) %>%
layer_points(fill = ~factor(Location)) %>%
scale_numeric("x", trans = "log", expand=0) %>%
scale_numeric("y", trans = "log", expand=0) %>%
add_axis("x", title = "blabla1") %>%
add_axis("y", title = "blabla2") %>%
add_tooltip(all_values, "hover")
What I would like to know is basically how to format the text shown interactively on the scatter plot.
Mainly I would like to:
Go on a new line after each parameter it is shown (the command "\n" in collapse and paste0 doesn't seem to work)
How to put in bold for example names(row)
You have to use the appropriate HTML tags in paste0():
For new line: collapse = "<br />"
For bold: "<b>", names(row), "</b>:"
Since you didn't provide a reproducible example, here's one with mtcars:
mtc <- mtcars
mtc$id <- 1:nrow(mtc) # Add an id column to use ask the key
all_values <- function(x) {
if(is.null(x)) return(NULL)
row <- mtc[mtc$id == x$id, ]
paste0("<b>", names(row), "</b>:", format(row), collapse = "<br />")
}
mtc %>%
ggvis(x = ~wt, y = ~mpg, key := ~id) %>%
layer_points() %>%
add_tooltip(all_values, "hover")

aggregating functions in ggvis add_tooltip

I am trying to add the frequency of each bar into a tooltip and am having issues. I attempted to use a group_by unsuccessfully. The tooltip returns a 4 for each tooltip for each bar.
mtcars %>%
ggvis(x = ~cyl) %>%
layer_histograms(fill="sky blue"
, fillOpacity:=.7
, fillOpacity.hover:=.9) %>%
group_by(cyl) %>%
add_tooltip(function(x) length(x))
This method has the same issue. It returns a 4 for each bar...
Freq <- function(x) {
paste0("Frequency: ", length(x))
}
mtcars %>%
ggvis(x = ~cyl) %>%
layer_histograms(fill="sky blue"
, fillOpacity:=.7
, fillOpacity.hover:=.9) %>%
group_by(cyl) %>%
add_tooltip(Freq)
To just quickly enable tool-tips with all values you can create a function all_values and add those.
all_values <- function(x) {
if(is.null(x)) return(NULL)
paste0(names(x), ": ", format(x), collapse = "<br />")
}
mtcars %>% group_by(cyl) %>%
ggvis(x = ~cyl) %>%
layer_histograms(fill="sky blue"
, fillOpacity:=.7
, fillOpacity.hover:=.9) %>%
add_tooltip(all_values, "hover")
You can use that information to piece together a function for what you actually want to show. In this case, just the upper value of the piece of the stacked bar chart.
mtcars %>% group_by(cyl) %>%
ggvis(x = ~cyl) %>%
layer_histograms(fill="sky blue"
, fillOpacity:=.7
, fillOpacity.hover:=.9) %>%
add_tooltip(function(df) (df$stack_upr_),"hover")

Resources