7

I'm able to plot a density histogram, and I'm able to plot a regular histogram with custom bins, but not both together. Here's my attempt:

library(ggplot2)

vals = c(2.6, 5.2, 4.1, 6.9, 5.7, 5.2, 4.4, 5.5, 6.3, 6.1, 4.7, 1.4)
myplot = qplot(vals, geom = 'blank') +   
         geom_line(aes(y = ..density..), stat = 'density',
                   colour = 26, size = 2, alpha = .6) +                     
         geom_histogram(aes(y = ..density..), binwidth = 1,
                        fill = 28, alpha = 0.3) +
         stat_bin(breaks=seq(-.5,8.5,1)) + xlim(-1, 9)

print(myplot)

If you remove the stat_bin term, the histogram plots correctly as a density histogram, but with default bin locations. Add the stat_bin term, and the bins are correct but it's no longer a density histogram. Any ideas how to get both working?

rcs
  • 67,191
  • 22
  • 172
  • 153
user1956609
  • 2,132
  • 5
  • 27
  • 43

1 Answers1

20

You can add argument breaks= to the geom_histogram() to set your own break points (you don't have to use geom_histogram() and stat_bin() together because geom_histogram() uses stat_bin() to produce result).

qplot(vals, geom = 'blank') +   
  geom_line(aes(y = ..density..), colour=26, stat = 'density', size = 2, alpha = .6) + 
  geom_histogram(aes(y = ..density..), fill = 28, alpha = 0.3, breaks=seq(-.5,8.5,1))

enter image description here

Didzis Elferts
  • 95,661
  • 14
  • 264
  • 201
  • If this is "exactly what you were looking for", could you accept this answer? Click the green tick just below the voting buttons. – Andy Clifton Nov 27 '13 at 06:53