Created
December 26, 2014 17:28
-
-
Save RCura/a135446cda079f4fbc10 to your computer and use it in GitHub Desktop.
ggvis issue - multiple layers on different dataset
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Create dummy data | |
a <- rnorm(n = 100, mean = 50, sd = 5) | |
b <- rnorm(n = 100, mean = 50, sd = 5) | |
c <- rnorm(n = 100, mean = 50, sd = 5) | |
mydf <- data.frame(A = a, B = b, C = c, row.names = c(1:100)) | |
library(ade4) | |
# Running a Correspondence Analysis | |
myCA <- dudi.coa(df = mydf,scannf = FALSE, nf = 2) | |
# Getting distances for Hclust | |
myDist <- dist.dudi(myCA, amongrow = TRUE) | |
# Doing the hclust | |
myClust <- hclust(d = myDist, method = "ward.D2") | |
# Cutting it at 3 | |
myClusters <- cutree(tree = myClust, k = 3) | |
# Plot through ggplot2 | |
myCAdata <- data.frame(Axis1 = myCA$li$Axis1, Axis2 = myCA$li$Axis2, Cluster = as.factor(myClusters)) | |
# Compute Standard Deviation Ellipse | |
library(ellipse) | |
df_ellipse <- data.frame() | |
for(g in levels(myCAdata$Cluster)){ | |
df_ellipse <- rbind(df_ellipse, | |
cbind(as.data.frame( | |
with(myCAdata[myCAdata$Cluster==g,], | |
ellipse(cor(Axis1, Axis2), | |
level=0.7, | |
scale=c(sd(Axis1),sd(Axis2)), | |
centre=c(mean(Axis1),mean(Axis2))))), | |
Cluster=g)) | |
} | |
# Plot data | |
library(ggplot2) | |
myPlot <- ggplot(data=myCAdata, aes(x=Axis1, y=Axis2,colour=Cluster)) + | |
geom_point(size=1.5, alpha=.6) + | |
geom_vline(xintercept = 0, colour="black",alpha = 0.5, linetype = "longdash" ) + | |
geom_hline(xintercept = 0, colour="black", alpha = 0.5, linetype = "longdash" ) + | |
geom_path(data=df_ellipse, aes(x=x, y=y,colour=Cluster), size=0.5, linetype=1) | |
myPlot | |
# Try through ggvis | |
library(ggvis) | |
# Create popover function | |
all_values <- function(x) { paste0(names(x), ": ", format(x), collapse = "<br />")} | |
ggDF <- myCAdata | |
ggDF$name <- row.names(ggDF) | |
## Coordinates plot | |
myCoordPlot <- ggvis(x = ~Axis1, y = ~Axis2, key := ~name, data = ggDF) %>% | |
layer_points(size := 15, fill= ~Cluster, data = ggDF) %>% | |
add_tooltip(all_values, "hover") | |
myCoordPlot | |
## Ellipses plot (no tooltip requested) | |
myEllPlot <- ggvis(data = df_ellipse, x = ~x, y = ~ y) %>% | |
group_by(Cluster) %>% | |
layer_paths(x= ~x, y= ~y, stroke = ~Cluster, strokeWidth := 1) | |
myEllPlot | |
## Trying to get both | |
myFullPlot <- ggvis(data = df_ellipse, x = ~x, y = ~ y) %>% | |
layer_paths(x= ~x, y= ~y, stroke = ~Cluster, strokeWidth := 1) %>% | |
layer_points(x = ~Axis1, y= ~Axis2, size := 15, fill= ~Cluster, data = ggDF) %>% | |
add_tooltip(all_values, "hover") | |
myFullPlot ### Seems ok, but layer_paths isn't grouped. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment