2
votes

I have a random vector, and trying to make density plot of it using ggplot here is the vector

fridayKlient1<-c(134 ,135, 133, 137, 136)

then i used density over it

res<-density(data)

then i try to convert the result of density to data.frame to prepare for ploting:

  framer<-function(data){return  (data.frame(y=data$y, x=data$x)) }

and then plot it

res<-framer(density(fridayKlient1)) 
ggplot() + 
  geom_density(aes(x=x,y=y), colour="red" , data=res)

. but it complains with:

ggplot2: object 'y' not found
3
The returned object is a list with several components in addition to the x and y values of the density estimate (run str(res) to see what else is in the list). I think you just need res1 = data.frame(res$x, res$y). - eipi10
Or if you really just want to plot it, plot(density(data)) - G5W
@G5W no i want to overlay some layers so i need to use ggplot() + geom_density - Sal-laS
OK, then the comment of @eipi should work for you. - G5W

3 Answers

0
votes

In order to plot the density of a given series, use geom_density. In order to plot an already existing density object, use geom_line.

fridayKlient1 <- c(134 ,135, 133, 137, 136)

res <- density(fridayKlient1)

# plot the results of the density call
ggplot(data.frame(x = res$x, y = res$y)) + 
  aes(x = x, y = y) + geom_line()

# plot the density using ggplot density method
ggplot(data.frame(x = fridayKlient1)) + 
  aes(x = x) + geom_density() + scale_x_continuous(limits = c(130, 140))
-1
votes

See str(res) for all components.

> head(data.frame(x = res$x, y = res$y))
         x            y
1 130.0792 0.0009454737
2 130.0985 0.0010042050
3 130.1178 0.0010641591
4 130.1370 0.0011299425
5 130.1563 0.0011970552
6 130.1755 0.0012693376

But to plot the density object in ggplot2, you would do

ggplot(data.frame(x = fridayKlient1), aes(x = x)) +
  geom_density()
-1
votes
ggplot(data = res, aes(x=x)) + 
  geom_density( colour="red" )

This should solve your problem. See geom_density() in ggplot2 docs. Else, go here.