1

I plot a histogram with two densities using ggplot2 with this code:

ggplot(khstat_wide, aes(x=khstat_vorher)) + geom_histogram(aes(y=..density..),binwidth=200) +
ylim(0,0.004) + xlim(0,10000) + scale_colour_brewer(palette="Dark2") +
stat_function(fun = dtweedie, aes(colour = 'Tweedie'), args = list(xi=round(out3$p.max,4), mu=mean(khstat_wide$khstat_vorher),phi=out3$phi.max)) +
theme(title=element_text(size=14),axis.text=element_text(size=12), legend.text=element_text(size=12),
    legend.position=c(.85,.85), legend.title=element_blank()) +
stat_function(fun = dgamma, aes(colour = 'Gamma' ), args = list(shape=1.199157e-01, scale=1.138242e+04 )) 

enter image description here

note that I set ylim(0,0.004) + xlim(0,10000) but doing so changes the scale of my histograms as values out of this range are omitted.

Here is the same plot with coord_cartesian(ylim=c(0,0.004),xlim=c(0,5000)) instead, but now the density lines look real "edgy":

enter image description here

how can I make them smooth again?

UPDATE:

It's hard building a reproducible example, here's a try:

a <- rgamma(500, shape=0.5)
b <- rep(0,300)
df <- data.frame(V1=c(a,b), V2=0)

works:

ggplot(df, aes(x=V1)) + geom_histogram(aes(y=..density..),binwidth=200) +
 ylim(0,0.01) + xlim(0,1000) + scale_colour_brewer(palette="Dark2") +
stat_function(fun = dgamma, aes(colour = 'Gamma' ), args =   list(shape=1.199157e-01, scale=1.138242e+04 )) 

does not work:

ggplot(df, aes(x=V1)) +  geom_histogram(aes(y=..density..),binwidth=200) +
scale_colour_brewer(palette="Dark2") +
stat_function(fun = dgamma, aes(colour = 'Gamma' ), args =  list(shape=1.199157e-01, scale=1.138242e+04 )) +
coord_cartesian(ylim=c(0,0.01),xlim=c(0,1000))
spore234
  • 3,550
  • 6
  • 50
  • 76
  • It would help if you supplied some of your data. – Heroka Sep 23 '15 at 08:29
  • @Heroka sorry, the data is confidential – spore234 Sep 23 '15 at 08:54
  • 2
    Then you could provide sample data. It's easier to help if there is some (similar) data to play with. Here are some [tips:](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – Heroka Sep 23 '15 at 08:55

1 Answers1

0

This solved the problem for me.

First, create an object of your original plot

p <- ggplot(df, aes(x=V1)) + geom_histogram(aes(y=..density..),binwidth=200) +
  scale_colour_brewer(palette="Dark2") +
  stat_function(fun = dgamma, aes(colour = 'Gamma' ), args =   list(shape=1.199157e-01, scale=1.138242e+04 )) +
  ylim(0,0.01) + xlim(0,1000)

Now use coord_cartesian() with the limits you want

p + coord_cartesian(ylim=c(0,0.01),xlim=c(0,500))

enter image description here

rafa.pereira
  • 13,251
  • 6
  • 71
  • 109