1 #-------------------------------------------------------------------------------
2 # Copyright (c) 2012 University of Illinois, NCSA.
3 # All rights reserved. This program and the accompanying materials
4 # are made available under the terms of the
5 # University of Illinois/NCSA Open Source License
6 # which accompanies this distribution, and is available at
7 # http://opensource.ncsa.illinois.edu/license.html
8 ##' Variable-width (dagonally cut) histogram
10 ##' When constructing a histogram, it is common to make all bars the same width.
11 ##' One could also choose to make them all have the same area.
12 ##' These two options have complementary strengths and weaknesses; the equal-width histogram oversmooths in regions of high density, and is poor at identifying sharp peaks; the equal-area histogram oversmooths in regions of low density, and so does not identify outliers.
13 ##' We describe a compromise approach which avoids both of these defects. We regard the histogram as an exploratory device, rather than as an estimate of a density.
15 ##' @title Diagonally Cut Histogram
16 ##' @param x is a numeric vector (the data)
17 ##' @param a is the scaling factor, default is 5 * IQR
18 ##' @param nbins is the number of bins, default is assigned by the Stuges method
19 ##' @param rx is the range used for the left of the left-most bin to the right of the right-most bin
20 ##' @param eps used to set artificial bound on min width / max height of bins as described in Denby and Mallows (2009) on page 24.
21 ##' @param xlab is label for the x axis
22 ##' @param plot = TRUE produces the plot, FALSE returns the heights, breaks and counts
23 ##' @param lab.spikes = TRUE labels the \% of data in the spikes
24 ##' @return list with two elements, heights of length n and breaks of length n+1 indicating the heights and break points of the histogram bars.
25 ##' @author Lorraine Denby, Colin Mallows
26 ##' @references Lorraine Denby, Colin Mallows. Journal of Computational and Graphical Statistics. March 1, 2009, 18(1): 21-31. doi:10.1198/jcgs.2009.0002.
27 dhist <- function(x, a=5*iqr(x), nbins=nclass.Sturges(x),
28 rx = range(x,na.rm = TRUE), eps=.15, xlab = "x", plot = TRUE,lab.spikes = TRUE){
29 if(is.character(nbins))
30 nbins <- switch(casefold(nbins), sturges = nclass.Sturges(x), fd = nclass.FD(x), scott = nclass.scott(x),
31 stop("Nclass method not recognized"))
32 else if(is.function(nbins))
35 x <- sort(x[!is.na(x)])
37 a <- diff(range(x))/100000000
38 if(a != 0 & a != Inf) {
40 h <- (rx[2] + a - rx[1])/nbins
41 ybr <- rx[1] + h * (0:nbins)
42 yupper <- x + (a * (1:n))/n
43 # upper and lower corners in the ecdf
44 ylower <- yupper - a/n
46 cmtx <- cbind(cut(yupper, breaks = ybr), cut(yupper, breaks = ybr, left.include = TRUE), cut(ylower, breaks = ybr),
47 cut(ylower, breaks = ybr, left.include = TRUE))
48 cmtx[1, 3] <- cmtx[1, 4] <- 1
49 # to replace NAs when default r is used
50 cmtx[n, 1] <- cmtx[n, 2] <- nbins
51 #checksum <- apply(cmtx, 1, sum) %% 4
52 checksum <- (cmtx[, 1] + cmtx[, 2] + cmtx[, 3] + cmtx[, 4]) %% 4
53 # will be 2 for obs. that straddle two bins
54 straddlers <- (1:n)[checksum == 2]
55 # to allow for zero counts
56 if(length(straddlers) > 0) {
57 counts <- table(c(1:nbins, cmtx[ - straddlers, 1]))
59 counts <- table(c(1:nbins, cmtx[, 1]))
63 if(length(straddlers) > 0) {
64 for(i in straddlers) {
66 theta <- ((yupper[i] - ybr[binno]) * n)/a
67 counts[binno - 1] <- counts[binno - 1] + (1 - theta)
68 counts[binno] <- counts[binno] + theta
72 xbr[-1] <- ybr[-1] - (a * cumsum(counts))/n
73 spike<-eps*diff(rx)/nbins
74 flag.vec<-c(diff(xbr)<spike,F)
75 if ( sum(abs(diff(xbr))<=spike) >1) {
78 diff.xbr<-abs(diff(xbr))
79 amt.spike<-diff.xbr[length(diff.xbr)]
80 for (i in rev(2:length(diff.xbr))) {
81 if (diff.xbr[i-1] <= spike&diff.xbr[i] <= spike & !is.na(diff.xbr[i])) {
82 amt.spike <- amt.spike+diff.xbr[i-1]
83 counts.new[i-1] <- counts.new[i-1]+counts.new[i]
88 else amt.spike<-diff.xbr[i-1]
90 flag.vec<-flag.vec[!is.na(xbr.new)]
91 flag.vec<-flag.vec[-length(flag.vec)]
92 counts<-counts.new[!is.na(counts.new)]
93 xbr<-xbr.new[!is.na(xbr.new)]
96 else flag.vec<-flag.vec[-length(flag.vec)]
97 widths <- abs(diff(xbr))
98 ## N.B. argument "widths" in barplot must be xbr
99 heights <- counts/widths
101 bin.size <- length(x)/nbins
102 cut.pt <- unique(c(min(x) - abs(min(x))/1000, approx(seq(length(x)), x,
103 (1:(nbins - 1)) * bin.size, rule = 2)$y, max(x)))
104 aa <- hist(x, breaks = cut.pt, plot = FALSE, probability = TRUE)
110 q75<-quantile(heights,.75)
111 if (sum(flag.vec)!=0) {
112 amt<-max(heights[!flag.vec])
113 ylim.height<-amt*amt.height
114 ind.h<-flag.vec&heights> ylim.height
115 flag.vec[heights<ylim.height*(amt.height-1)/amt.height]<-F
116 heights[ind.h] <- ylim.height
121 barplot(heights, abs(diff(xbr)), space = 0, density = -1, xlab = xlab, plot = TRUE, xaxt = "n",yaxt='n')
123 axis(1, at = at - xbr[1], labels = as.character(at))
125 if (sum(flag.vec)>=1) {
127 for ( i in seq(length(xbr)-1)) {
130 if (xbr[i]-xbr[1]<end.y) amt.txt<-1
134 end.y<-xbr[i]-xbr[1]+3*par('cxy')[1]
137 txt<-paste(' ',format(round(counts[i]/
138 sum(counts)*100)),'%',sep='')
140 text(xbr[i+1]-xbr[1],ylim.height-par('cxy')[2]*(amt.txt-1),txt, adj=0)
143 } else print('no spikes or more than one spike')
145 invisible(list(heights = heights, xbr = xbr))
146 } else {return(list(heights = heights, xbr = xbr,counts=counts))}
148 #==================================================================================================#
149 ##' Calculate interquartile range
151 ##' Calculates the 25th and 75th quantiles given a vector x; used in function \link{dhist}.
153 ##' @title Interquartile range
155 ##' @return numeric vector of length 2, with the 25th and 75th quantiles of input vector x.
157 return(diff(quantile(x, c(0.25, 0.75), na.rm = TRUE)))
159 ##==================================================================================================#
160 ##' Creates empty ggplot object
162 ##' An empty base plot to which layers created by other functions
163 ##' (\code{\link{plot.data}}, \code{\link{plot.prior.density}},
164 ##' \code{\link{plot.posterior.density}}) can be added.
165 ##' @name create.base.plot
166 ##' @title Create Base Plot
167 ##' @return empty ggplot object
169 ##' @author David LeBauer
170 create.base.plot <- function() {
171 base.plot <- ggplot()
174 #==================================================================================================#
175 ##' Add data to an existing plot or create a new one from \code{\link{create.base.plot}}
177 ##' Used to add raw data or summary statistics to the plot of a distribution.
178 ##' The height of Y is arbitrary, and can be set to optimize visualization.
179 ##' If SE estimates are available, tehse wil be plotted
181 ##' @title Add data to plot
182 ##' @param trait.data data to be plotted
183 ##' @param base.plot a ggplot object (grob),
184 ##' created by \code{\link{create.base.plot}} if none provided
185 ##' @param ymax maximum height of y
186 ##' @seealso \code{\link{create.base.plot}}
187 ##' @return updated plot object
188 ##' @author David LeBauer
191 ##' \dontrun{plot.data(data.frame(Y = c(1, 2), se = c(1,2)), base.plot = NULL, ymax = 10)}
192 plot.data <- function(trait.data, base.plot = NULL, ymax, color = 'black') {
193 if(is.null(base.plot)) base.plot <- create.base.plot()
194 n.pts <- nrow(trait.data)
197 } else if (n.pts < 5) {
202 y.pts <- seq(0, ymax, length.out = 1 + n.pts)[-1]
203 plot.data <- data.frame(x = trait.data$Y, y = y.pts, se = trait.data$se,
204 control = !trait.data$trt == 1 & trait.data$ghs == 1)
205 new.plot <- base.plot + geom_point(data = plot.data, aes(x = x, y = y, color = control)) +
206 geom_segment(data = plot.data, aes(x = x - se, y = y, xend = x + se, yend = y, color = control)) +
207 scale_color_manual(values = c('black', 'grey')) + opts(legend_position = "none")
210 ##==================================================================================================#
211 ##' Add borders to .. content for \description{} (no empty lines) ..
213 ##' Has ggplot2 display only specified borders, e.g. ("L"-shaped) borders, rather than a rectangle or no border. Note that the order can be significant; for example, if you specify the L border option and then a theme, the theme settings will override the border option, so you need to specify the theme (if any) before the border option, as above.
214 ##' @name theme_border
215 ##' @title Theme border for plot
220 ##' @return adds borders to ggplot as a side effect
221 ##' @author Rudolf Cardinal
222 ##' @author \url{ggplot2 google group}{https://groups.google.com/forum/?fromgroups#!topic/ggplot2/-ZjRE2OL8lE}
225 ##' df = data.frame( x=c(1,2,3), y=c(4,5,6) )
226 ##' ggplot(data=df, aes(x=x, y=y)) + geom_point() + theme_bw() +
227 ##' opts(panel.border = theme_border(c("bottom","left")) )
228 ##' ggplot(data=df, aes(x=x, y=y)) + geom_point() + theme_bw() +
229 ##' opts(panel.border = theme_border(c("b","l")) )
231 theme_border <- function(type = c("left", "right", "bottom", "top", "none"), colour = "black", size = 1, linetype = 1){
232 type <- match.arg(type, several.ok=TRUE)
233 structure(function(x = 0, y = 0, width = 1, height = 1, ...) {
237 if ("bottom" %in% type) { # bottom
238 xlist <- append(xlist, c(x, x+width))
239 ylist <- append(ylist, c(y, y))
240 idlist <- append(idlist, c(1,1))
242 if ("top" %in% type) { # top
243 xlist <- append(xlist, c(x, x+width))
244 ylist <- append(ylist, c(y+height, y+height))
245 idlist <- append(idlist, c(2,2))
247 if ("left" %in% type) { # left
248 xlist <- append(xlist, c(x, x))
249 ylist <- append(ylist, c(y, y+height))
250 idlist <- append(idlist, c(3,3))
252 if ("right" %in% type) { # right
253 xlist <- append(xlist, c(x+width, x+width))
254 ylist <- append(ylist, c(y, y+height))
255 idlist <- append(idlist, c(4,4))
257 polylineGrob(x=xlist, y=ylist, id=idlist, ..., default.units = "npc",
258 gp=gpar(lwd=size, col=colour, lty=linetype),
266 #==================================================================================================#