[英]how to extract and plot density using ggplot2
我有一个随机向量,并尝试使用 ggplot 使它的密度为 plot 这里是向量
fridayKlient1<-c(134 ,135, 133, 137, 136)
然后我在上面使用了密度
res<-density(data)
然后我尝试将density
结果转换为 data.frame 以准备绘图:
framer<-function(data){return (data.frame(y=data$y, x=data$x)) }
然后 plot 它
res<-framer(density(fridayKlient1))
ggplot() +
geom_density(aes(x=x,y=y), colour="red" , data=res)
. 但它抱怨:
ggplot2: object 'y' not found
为了 plot 给定系列的密度,请使用geom_density
。 为了 plot 一个已经存在的密度 object,使用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))
有关所有组件,请参见str(res)
。
> 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
但是要在ggplot2中绘制密度对象,您可以
ggplot(data.frame(x = fridayKlient1), aes(x = x)) +
geom_density()
ggplot(data = res, aes(x=x)) +
geom_density( colour="red" )
这应该可以解决您的问题。 请参阅ggplot2文档中的geom_density()。 否则,去这里 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.