簡體   English   中英

如何使用 ggplot2 提取和 plot 密度

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM