Skip to content

Instantly share code, notes, and snippets.

@nassimhaddad
Last active August 29, 2015 14:02
Show Gist options
  • Save nassimhaddad/cd53b1d4ed5a23e50900 to your computer and use it in GitHub Desktop.
Save nassimhaddad/cd53b1d4ed5a23e50900 to your computer and use it in GitHub Desktop.
interactive scatterplot in r with tooltips
interactiveScatter <- function(xvar, yvar, data,
tooltip = c(xvar, yvar), title = "",
lmline = TRUE){
require(rCharts)
x <- xvar
y <- yvar
tooltipString <- paste0("#!function(item){return ",
paste(paste0("item.", tooltip), collapse = "+' '+"),
"}!#")
formula <- as.formula(sprintf("%s ~ %s", y, x))
if (lmline){
reg <- (lm(formula,data))
data$fittedlmForchart <- predict(reg)
}
p1 <- rPlot(formula, data = data, type = 'point',
tooltip = tooltipString)
if (lmline){
p1$layer(y = 'fittedlmForchart', copy_layer = T, type = 'line',
color = list(const = 'red'))
}
p1$set( title = title )
p1$guides(
x = list(
min = pretty( data[, x] ) [1],
max = tail( pretty( data[, x] ), 1 ),
numticks = length( pretty( data[, x] ) ),
labels = pretty( data[, x] )
),
y = list(
min = pretty( data[, y] ) [1],
max = tail( pretty( data[, y] ), 1 ),
numticks = length( pretty( data[, y] ) ),
labels = pretty( data[, y] )
)
)
return(p1)
}
x = rnorm(20, 5, 1)
data <- data.frame(x,
y = 2+3*x+rnorm(20, 0, 2),
names = letters[1:20])
interactiveScatter("x", "y", data = data,
tooltip = c("names", "x", "y"), lmline=T,
title = "random data")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment