Search code examples
rggplot2histogram

Adding a geom_line to histogram for single factor in R


Im trying to add a line to the histogram on the level where group == 1

ggplot(dat, aes(x=age, fill=group)) +
    geom_histogram(binwidth=10, position="dodge")

I tried a lot of different things but I cant seem to make it work.

Maybe it's not geom_line but something else ?

ideally i should have something like this


Solution

  • Seems like you want to add density on your histogram.
    Using diamonds data as an example,

    ggplot(diamonds, aes(x=price, y=..density..,fill=cut))+
      geom_histogram(position='dodge')+
      geom_density(data=diamonds[diamonds$cut=='Ideal',],alpha=.4)
    

    enter image description here