[R] Histograms with bin proportions on the y-axis

(Ted Harding) Ted.Harding at wlandres.net
Sun May 20 23:27:17 CEST 2012


See in-line below.

On 20-May-2012 19:07:55 Nick Gayeski wrote:
> I have what is probably a simple problem. I have a data file
> from an MCMC Bayes estimation problem that is a vector of 500,000
> numeric values (just one variable) ranging from 100,000 to 700,000.
> I need to display the histogram of this data in a high quality
> graphic for a figure in a journal publication. I want 100 bins
> so as to display a reasonable complete and smooth histogram,
> and I need the Y-axis to display the bin proportions.
> 
> I'm new to all of the graphics capabilities of R.
> 
> Can anyone provide me with the command I need to issue to the call
> to hist to get the output that I desire?

The following illustrates how to "customise" the behaviour of
hist() to achieve a desired effect (such as the one you want):

  N <- 500000   ## sample size
  Y <- rnorm(N,mean=400000,sd=100000)  ## the sample
  ## Now make a non-plotted object which contains the histogram info:
  H0 <- hist(Y,breaks=100,plot=FALSE)  ## the bin values are counts
  C <- H0$counts ## extract the counts
  ## Now convert these to proportions (percent or fraction as you wish):
  P <- 100*C/N  ## or P <- C/N for fractional proportions
  ## Now copy the histigram object H0 to H1 and modify H1:
  H1 <- H0 ; H1$counts <- P  ## replaces the "counts" by the proportions
  ## Now plot it:
  plot(H1,ylab="% proportions in bins")

> I assume that once I have the desired histogram I will be able to
> save it in a format like .eps that will permit it to be reproduced
> in high resolution. But any suggestions for this task would also
> be appreciated.
> 
> Regards,
> Nick

As Michael Weylandt has suggested, you can encapsulate the final
plot() command between the opening of a graphics device and the
closure of the device. So if you want an EPS file you can use the
postscript device:

  postscript("myhistoplot.eps",horizontal=FALSE)
  plot(H1,ylab="% proportions in bins")
  dev.off()

and the result will be an EPS file "myhistoplot.eps". You will
probably want to at least vary the aspect ratio (height:width)
and maybe some other things, so give the command

  ?postscript

to find out what the various (and many .. ) options are.

Hoping this helps to get you started!
Ted.

-------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at wlandres.net>
Date: 20-May-2012  Time: 22:27:13
This message was sent by XFMail



More information about the R-help mailing list