'how to extract and plot density using ggplot2
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
Solution 1:[1]
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))
Solution 2:[2]
ggplot(data = res, aes(x=x)) +
geom_density( colour="red" )
This should solve your problem. See geom_density() in ggplot2 docs. Else, go here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mzuba |
| Solution 2 | Globox |
