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

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")

Related

how to display selectedinput to plot title for shiny

output$selected <- renderText({
paste(input$name)
})
output$hcontainer8 <- renderHighchart({
var <- textOutput("selected")
hc2 <- df_clean %>% filter(df_clean$ManagerName == input$name)
hchart(hc2, "lollipop", hcaes(name = Employee_Name, low = Absences ),name = "Absences") %>%
hc_xAxis(type = "category") %>%
hc_yAxis(labels = list(format = "{value}")) %>%
hc_title(text="Employee Absences under {var}",align="center") %>%
hc_subtitle(text = "with mean value from each department group by Performance Score", align = "center")
})
so this is my code for the server.r and I want to show the manager name in the plot title
based on the selected input
(text="Employee Absences under {var}",align="center")
this is a closer look at the code, so I want to display it in {var} is there a way to do it?
input$name is a string that you can use to both filter and within the hc_title() call.
Try:
hc_title(text = paste0("Employee Absences under ", input$name), align="center") %>%

R ggvis format tooltip using percentages

I'm using the ggvis package in R to build a build a horizontal stack bar. In the tooltip, I want to add both the absolute and relative values (in percentages).
The following code works, but the tooltip is not formatted correctly yet:
all_values <- function(x) {
if(is.null(x)) return(NULL)
#x[,sapply(x, is.double)] <- apply(x[,sapply(x, is.double)], 1, function(x) {paste(round(100*x, 2), "%", sep="")})
paste0(names(x), ": ",format(x), collapse = "<br />")
}
df <- data.frame(a = c('a','b','c'), v1 = c(7,2,1), v2 = c(0.7,0.2,0.1))
df %>% ggvis(x = ~v1, y = ~a, fill = ~v2) %>%
layer_rects(x2 = 0, height = band()) %>%
add_tooltip(all_values, "hover") %>%
add_tooltip(all_values, "click")
I want to format v2 in such a way that it shows percentages in the tooltip.
The values themself (0.7 for example) should still be used as fill.
Removing the commented part in all_values let's the visual crash when hovering for some reason, even though the result of the function would be perfect to me.
Any suggestions?
Something like this?
library(ggvis)
all_values <- function(x) {
if(is.null(x)) return(NULL)
x <- paste0(x[,3]*100,"%")
paste0(names(x), "",format(x), collapse = "<br />")
}
df <- data.frame(a = c('a','b','c'), v1 = c(7,2,1), v2 = c(0.7,0.2,0.1))
df %>% ggvis(x = ~v1, y = ~a, fill = ~v2) %>%
layer_rects(x2 = 0, height = band()) %>%
add_tooltip(all_values, "hover") %>%
add_tooltip(all_values, "click")

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().

R ggvis linked_brush is not reactive

I have the following code on my Server. R
data_agg_plot1<- reactive({
brush1 <- linked_brush(keys = data_agg()$id, "navy" )
data_agg <- data_agg()
plot1<-data_agg%>%
ggvis(x = ~dates_all) %>%
group_by(factor(dates_all.1)) %>%
layer_points(y = ~ value, fill =~dates_all.1, shape =~dates_all.1) %>%
layer_paths(y = ~ value, stroke = ~dates_all.1 , strokeOpacity := 0.5) %>%
scale_ordinal("fill", range = c("green", "red", "blue"))%>%
scale_ordinal("shape", range = c("triangle-up","triangle-down","circle")) %>%
scale_ordinal("stroke",range=c("green","red","blue")) %>%
brush1$input() %>%
hide_legend(c('stroke','fill'))%>%
add_legend(c('shape','fill'),
title = "Symbol", orient = "left",
values = c("New hires", "Attrition" , "Net Growth"),
properties = legend_props(
title = list(fontSize = 16))) %>%
add_axis("x",properties= axis_props(labels = list(angle=60,align = "left")),
tick_padding =0,
title = "") %>%
add_axis("y", title = "Total Count") %>%
set_options(width = "auto",height = 400) %>%
scale_numeric('y',clamp = TRUE)
return(list(plot1,brush1))
})
so this is a reactive function that returns me a list of 2 functions, a plot and my brush object.
the purpose of doing so is so that I can make my keys reactive - this is so that I can make an additional plot based on my user's selection. think of it as the second plot depends on what the first user highlights in the first plot.
this is my following code:
plot1_data<-reactive({
data_agg_plot1()[[1]]
})
plot1_data%>%bind_shiny("plot1")
selected_plot1 <- reactive({
data_agg_plot1()[[2]]
})
output$test <- renderPrint({
temp <- selected_plot1()$selected()
print(temp)
})
however, when I print out the selection, it is all false,
please refer to the image below:
can anybody explain to me how to overcome this?
I highly suspect I have to re-write my linkedbrush function,
I have tried both solutions from:
linked_brush in ggvis cannot work in Shiny when data change
but it does not work.

Disappearing values in ggvis when using tooltip on grouped data

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

Resources