0

I have data that I made a histogram for (ur_memr_t$up...). I then used fitdistr to fit an exponential dist to the data. I captured the parameters for the fitted distribution and generated some random variates. I then made a density curve for the exp random variates. I want to place the density over the histogram. The following code throws this error

  exp_data <- data.frame( x = rexp(3000, rate = 0.0144896182))

  ggplot(data = ur_memr_t, aes(ur_memr_t$updated_days_to_next_ur)) + 
  geom_histogram() + ggplot(exp_data, aes(x)) + geom_density()

Error in p + o : non-numeric argument to binary operator
In addition: Warning message:
Incompatible methods ("+.gg", "Ops.data.frame") for "+"

If I run

  ggplot(data = ur_memr_t, aes(ur_memr_t$updated_days_to_next_ur)) + 
  geom_histogram()

and

  ggplot(exp_data, aes(x)) + geom_density()

seperately, they produce correct plots. Why will they not work together and plot one on top of the other?

mbs1
  • 317
  • 1
  • 3
  • 12
  • it would be helpful if you created a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Since we don't have access to `um_memr_t`, we cannot run your code. You cannot add two `ggplot` objects. Typically you just add new layers with different data sources and mappings. Something like `ggplot() + geom_histogram(data=ur_memr_t, aes(updated_days_to_next_ur, ..density..)) + geom_density(data=exp_data, aes(x), color="red")` should be close. Note that counts and densities are on different scales – MrFlick Feb 16 '16 at 21:51
  • Also this question is asked often. I'd recommend searching for similar answers: http://stackoverflow.com/questions/5688082/ggplot2-overlay-histogram-with-density-curve – MrFlick Feb 16 '16 at 21:54

1 Answers1

1

I think it should work but you can only have one ggplot statement. Try something like this:

g = ggplot(data = ur_memr_t, aes(updated_days_to_next_ur)) 
g = g + geom_histogram(aes(updated_days_to_next_ur))
g = g + geom_density(data = exp_data, aes(x)) 

Hope it helps

MrFlick
  • 195,160
  • 17
  • 277
  • 295
Charles Stangor
  • 292
  • 7
  • 21