Tim_Utrecht
Tim_Utrecht

Reputation: 1519

Two distributions in with googleVis in R

I'm trying to get two distributions in one graph with the googlevis function gvisAreaChart but it is not working as I want:

 library(googleVis)
 df <- data.frame(a=rnorm(n = 400,mean = .1,sd = .01),b=rnorm(n = 400,mean = .13,sd = .01))
 dfplot <- rbind(data.frame(x=density(df$a)$x,y=density(df$a)$y,var=rep("a",512)),data.frame(x=density(df$b)$x,y=density(df$b)$y,var=rep("b",512)))
 plot(gvisAreaChart(dfplot,xvar = 'x',yvar='y'))  

I would like to give the two distributions different colors and also when they overlap. I know this is possible in ggplot but I'm looking for a solution with googleVis because it works better with Shiny.

Thanks.

EDIT: Found very cumbersome workaround:

 dfplot <- data.table(x=seq(0,by = .001))
 df <- data.table(a=rnorm(n = 400,mean = .1,sd = .01),b=rnorm(n = 400,mean = .13,sd = .01))
 dfa <- data.table(x=round(density(df$a)$x,3),y1=density(df$a)$y,var=rep("a",512))
 dfb <- data.table(x=round(density(df$b)$x,3),y2=density(df$b)$y,var=rep("b",512))

 dfa[duplicated(x),test:=TRUE];dfa<-dfa[is.na(test)]
 dfb[duplicated(x),test:=TRUE];dfb<-dfb[is.na(test)] 

 setkey(dfplot,x);setkey(dfa,x);setkey(dfb,x)
 merge <- merge(dfplot,dfa,all.x=T,all.y=F,allow.cartesian=T)
 merge <- merge(merge,dfb,all.x=T,all.y=F,allow.cartesian=T)

 merge <- merge[,max:=pmax(y1,y2,na.rm=T)]
 merge <- merge[!is.na(max)]
 merge<-subset(merge,select = c('x','y1','y2'))

 plot(gvisAreaChart(merge,xvar = 'x',yvar=c('y1','y2')))

Upvotes: 1

Views: 118

Answers (1)

Pork Chop
Pork Chop

Reputation: 29387

unfortunately I am not that familiar with googleVis, but hopefully you can accept the solution with rCharts

rm(list = ls())
library(shiny)
library(rCharts)

df <- data.frame(a=rnorm(n = 400,mean = .1,sd = .01),b=rnorm(n = 400,mean = .13,sd = .01))
dfplot <- rbind(data.frame(x=density(df$a)$x,y=density(df$a)$y,var=rep("a",512)),data.frame(x=density(df$b)$x,y=density(df$b)$y,var=rep("b",512)))
hPlot(x = "x", y = "y", group = "var", data = dfplot, type = "area")

enter image description here

Upvotes: 1

Related Questions