1

I am using ggplot2 to draw a histogram of a sample of size 1000 taken from a normal distribution. I need to place the letter 'A' on the center of the histogram, and doing that with the function annotate.

Since this vector is random, the "center" of the drawing will change a little bit every time I run the code so I need to find a way in which the function knows how to place the 'A' according to that specific sample.For the x axis I took the median of the sample for the Y axis i was thinking of taking the frequency of the most frequent bin and dividing by 2.

Does anybody know if there is a function who gives you the frequency of each bin?

Here is a reproducible example:

library(ggplot2)
set.seed(123)
x <- rnorm(1000)
qplot(x, geom="histogram")
Vincent Guillemot
  • 3,394
  • 14
  • 21
Lee Neumann
  • 291
  • 1
  • 3
  • 3
  • 2
    Please read (1) [how do I ask a good question](http://stackoverflow.com/help/how-to-ask), (2) [How to create a MCVE](http://stackoverflow.com/help/mcve) as well as (3) [how to provide a minimal reproducible example in R](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example#answer-5963610). Then edit and improve your question accordingly. I.e., provide for example dummy input data, what lines of code you tried etc – lukeA May 10 '16 at 08:38

1 Answers1

3

Here is a way to get the coordinates of the output plot (on a reproducible example):

library(ggplot2)
x <- runif(10)
h <- qplot(x, geom="histogram")
ggplot_build(h)$data

This will give you all sorts of information on the histogram.

So to get the height of the most frequent class and divide by two, you just need to do

height <- max(ggplot_build(h)$data[[1]]$count) / 2

Using the same kind of information, you can also put the text always right in the middle of the plot:

ranges <- ggplot_build(h)$panel$ranges
xtext <- mean(ranges[[1]]$x.range)
ytext <- mean(ranges[[1]]$y.range)
h + annotate("text", xtext, ytext, 
  label="A", size=30, color="blue", alpha=0.5)
Vincent Guillemot
  • 3,394
  • 14
  • 21