4
votes

I am trying to do some density plots in R. I originally used density plot but I changed to the density plot in ggplot2 because I visually prefer ggplot2.

So I did a density plot using the density plot function and did a density plot in ggplot2 (see below) but I found the plots were not identical. It looks like some of the y-values have been lost or dropped in the ggplot2 (right plot). Is there any particular reason for this? How can I make the ggplot identical to the destiny plot (left plot).

enter image description here

Code:

library(ggplot2)
library(grid)
par(mfrow=c(1,2))

# define function to create multi-plot setup (nrow, ncol)
vp.setup <- function(x,y){
 grid.newpage()
 pushViewport(viewport(layout = grid.layout(x,y)))
}

# define function to easily access layout (row, col)
vp.layout <- function(x,y){
  viewport(layout.pos.row=x, layout.pos.col=y)
}


vp.setup(1,2)

dat <- read.table(textConnection("
low high
10611.0 14195.0
10759.0 14437.0
10807.0 14574.0
10714.0 14380.0
10768.0 14448.0
10601.0 14239.0
10579.0 14218.0
10806.0 14510.0
"), header=TRUE, sep="\t")

plot(density(dat$low))

dat.low = data.frame(low2 = c(dat$low), lines = rep(c("low")))

low_plot_gg = (ggplot(dat.low, aes(x = low2, fill = lines)) +
 stat_density(aes(y = ..density..)) + 
 coord_cartesian(xlim = c(10300, 11000)) 
)
print(low_plot_gg, vp=vp.layout(1,2))
2
Mixture of base and grid graphics not entirely successful.IRTFM

2 Answers

6
votes

Based on some trial and error, it looks like you want

 + xlim(c(10300,11000))

rather than

 + coord_cartesian(xlim = c(10300, 11000)) 

coord_cartesian extends the limits of the plots but doesn't change what's drawn inside them at all ...

0
votes

It's not a problem of lost values. The function plot(density()) proceed to smoothing for extreme value but it's not very accurate for your little dataset. For a bigger dataset the two plots will be the same.