4

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. Commented Aug 24, 2012 at 16:41
  • @Harpal You may also want to consult this answer. Commented Jan 19, 2022 at 21:51

2 Answers 2

6

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 ...

Sign up to request clarification or add additional context in comments.

1 Comment

D'oh, so missed the obvious here. Thanks for your help.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.