######################################################################
##
## Illustrative plot function for
##
##   Potts, Christopher. 2010. On the negativity of negation.
##   Proceedings of Semantics and Linguistic Theory 20.
##
## This program is released under Eclipse Public License - v 1.0:
##
##   http://www.eclipse.org/legal/epl-v10.html
##
## Created 2010-08-15; last update 2010-08-15
##
##
## Below is an R function for studying words in the data files
## associated with this paper. It works with both IMDB and EP, which
## necessitates a simpler visual design than is found in the paper,
## though the techniques and calculations are the same. The function
## is designed to be accessible to people without experience in R;
## usage examples are given in the README.txt file. The function
## requires the binom and Hmisc packages, which can be downloaded and
## installed easily using the R graphical interface. Also, R is by no
## means the only option; any program or language capable of reading
## in CSV files should work well with the data.
##
######################################################################

library(binom) # Flexible binomial tests.
library(Hmisc) # Error bars in plots.

## * df: table built with read.csv() from one of the distributed CSV files
## * word: any string
## * ymax: the top of the y-axis; the default is 0.4
saltPlot = function(df, word, ymax=0.4){
  ## Pull out just the rows matching (lower-cased) word.
  d = subset(df, Word == tolower(word))

  ## Exit if the word isn't in df.
  if(nrow(d)==0){print(paste("Ack:", word, "not in", csv)); return()}

  ## Conditional distributions.
  d$PrWC = d$Count / d$Total
  d$PrCW = d$PrWC / sum(d$PrWC)

  ## Confidence intervals with rescaling into the Pr(c|w) space.
  ci = binom.confint(d$Count, d$Total, method="exact")
  d$LCI = ci[,5] / sum(d$PrWC)
  d$UCI = ci[,6] / sum(d$PrWC)

  ## Basic plot with error bars.
  plot(d$Category, d$PrCW, axes=F, ylim=c(0,ymax), type="n", main=word)
  errbar(d$Category, d$PrCW, yplus=d$UCI, yminus=d$LCI, cap=0, add=T)

  ## Force all category labels to display.
  axis(1, at=seq(1:length(d$Category)), labels=d$Category)
  ## Tufte-inspired y-axis showing min and max values for word.
  axis(2, at=round(c(min(d$PrCW), median(d$PrCW), max(d$PrCW)), 2))

  ## Return word's frame for further analysis.
  return(d)
}

