r - How does ggplot2 density differ from the density function? -


why following plots different? both methods appear use gaussian kernels.

how ggplot2 compute density?

library(fueleconomy)  d <- density(vehicles$cty, n=2000) ggplot(null, aes(x=d$x, y=d$y)) + geom_line() + scale_x_log10() 

enter image description here

ggplot(vehicles, aes(x=cty)) + geom_density() + scale_x_log10() 

enter image description here


update:

a solution question appears on here, specific parameters ggplot2 passing r stats density function remain unclear.

an alternate solution extract density data straight ggplot2 plot, shown here

in case, not density calculation different how log10 transform applied.

first check densities similar without transform

library(ggplot2) library(fueleconomy)  d <- density(vehicles$cty, from=min(vehicles$cty), to=max(vehicles$cty)) ggplot(data.frame(x=d$x, y=d$y), aes(x=x, y=y)) + geom_line()  ggplot(vehicles, aes(x=cty)) + stat_density(geom="line") 

so issue seems transform. in stat_density below, seems if log10 transform applied x variable before density calculation. reproduce results manually have transform variable prior calculating density. eg

d2 <- density(log10(vehicles$cty), from=min(log10(vehicles$cty)),                                                 to=max(log10(vehicles$cty))) ggplot(data.frame(x=d2$x, y=d2$y), aes(x=x, y=y)) + geom_line()  ggplot(vehicles, aes(x=cty)) + stat_density(geom="line") + scale_x_log10() 

ps: see how ggplot prepares data density, can @ code as.list(statdensity) leads statdensity$compute_group ggplot2:::compute_density


Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -