Creating a density histogram in ggplot2?

fill=seg results in grouping. You are actually getting a different histogram for each value of seg. If you don't need the colours, you could use this:

ggplot(df) + 
  geom_histogram(breaks=breaks,aes(x=vector,y=..density..), position="identity") + 
  geom_density(aes(x=vector,y=..density..))

enter image description here

If you need the colours, it might be easiest to calculate the density values outside of ggplot2.


Manually, I added colors to your percentile bars. See if this works for you.

library(ggplot2)

ggplot(df, aes(x=vector)) +   
   geom_histogram(breaks=breaks,aes(y=..density..),colour="black",fill=c("red","orange","yellow","lightgreen","green","darkgreen","blue","darkblue","purple","pink")) + 
   geom_density(aes(y=..density..)) +
   scale_x_continuous(breaks=c(-3,-2,-1,0,1,2,3)) +
   ylab("Density") + xlab("df$vector") + ggtitle("Histogram of df$vector") +
   theme_bw() + theme(plot.title=element_text(size=20),
                      axis.title.y=element_text(size = 16, vjust=+0.2),
                      axis.title.x=element_text(size = 16, vjust=-0.2),
                      axis.text.y=element_text(size = 14),
                      axis.text.x=element_text(size = 14),
                      panel.grid.major = element_blank(),
                      panel.grid.minor = element_blank())

enter image description here