[R] A plot similar to violin plot

Jim Lemon jim at bitwrit.com.au
Wed Mar 9 08:27:34 CET 2011


On 03/08/2011 11:27 PM, C.H. wrote:
> Dear R Users,
>
> I would like to know is there any package to create a plot like this?
>
> http://dl.dropbox.com/u/5409929/cs1160521f01.gif
>
> X axis is categorical. And the positions of the points are
> corresponding to the frequency. (similar to violinplot)
>
Hi CH,
This looks like it uses the same method as in the function brkdn.plot in 
the plotrix package. What this does is to offset each value in a 
particular stack by a small amount to the right, then twice that amount 
to the left, then three times that amount to the right, and so on. This 
would spread your data points out for each bin of values. The plot looks 
as though the data points in each bin are sorted before spreading, so 
that the "branches" in each bin slant upward. Let's see:

x<-list(runif(90),runif(100),runif(80))

dendroPlot<-function(x,breaks=NA,nudge=NA) {
  if(is.na(breaks[1]))
   breaks=seq(min(unlist(x),na.rm=TRUE),
   max(unlist(x),na.rm=TRUE),length.out=10)
  plot(c(0,length(x)+1),range(unlist(x)),type="n")
  if(is.na(nudge)) nudge<-strwidth("o")/2
  for(list_element in 1:length(x)) {
   binvar<-cut(x[[list_element]],breaks=breaks)
   for(bin in 1:length(levels(binvar))) {
    thisbin<-which(as.numeric(binvar)==bin)
    offset<-(1:length(x[[list_element]][thisbin])-1)*nudge
    offset[seq(2,length(offset),by=2)]<-
     -offset[seq(2,length(offset),by=2)]
    points(list_element+offset,sort(x[[list_element]][thisbin]))
   }
  }
}

dendroPlot(x)

I think this might make it into plotrix. Let me know if it does what you 
want.

Jim



More information about the R-help mailing list