Skip to content

Instantly share code, notes, and snippets.

@yannabraham
Last active May 29, 2018 14:56
Show Gist options
  • Save yannabraham/5b71b9599b460968f72e9b7ae63868e7 to your computer and use it in GitHub Desktop.
Save yannabraham/5b71b9599b460968f72e9b7ae63868e7 to your computer and use it in GitHub Desktop.
Plotting Andrews curves using dplyr and ggplot2
## https://en.wikipedia.org/wiki/Andrews_plot
library(dplyr)
library(ggplot2)
do.andrews <- function(x,breaks=30) {
require(reshape2)
t <- seq(-pi, pi, pi/breaks)
m<-nrow(x)
n<-ncol(x)
f <- matrix(t,nrow=length(t),ncol=n)
j <- seq(2,n)
f[,j[j%%2==0]] <- sweep(f[,j[j%%2==0],drop=FALSE],
2,
j[j%%2==0]/2,
`*`)
f[,j[j%%2!=0]] <- sweep(f[,j[j%%2!=0],drop=FALSE],
2,
j[j%%2!=0]%/%2,
`*`)
f[,j[j%%2==0]] <- sin(f[,j[j%%2==0]])
f[,j[j%%2!=0]] <- cos(f[,j[j%%2!=0]])
f <- x[,j]%*%t(f[,j])
f <- f+matrix(x[,1]/2^0.5,nrow=m,ncol=length(t),byrow=F)
res <- melt(f,varnames=c('RowId','AndrewsId'),value.name = 'AndrewsValue')
res[,'AndrewsId'] <- t[res[,'AndrewsId']]
return(res)
}
iris %>%
group_by(Species) %>%
do({do.andrews(as.matrix(select(.,-Species)))}) %>%
ggplot(aes(x=AndrewsId,y=AndrewsValue,color=Species,group=interaction(Species,RowId)))+
geom_line(size=1.2)
iris %>%
group_by(Species) %>%
do({do.andrews(as.matrix(select(.,-Species)))}) %>%
group_by(Species,AndrewsId) %>%
summarize(AndrewsValue=mean(AndrewsValue)) %>%
ggplot(aes(x=AndrewsId,y=AndrewsValue,color=Species))+
geom_line(size=1.2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment