2015-10-08 51 views
0

我的數據ret包含3個變量,每個變量包含208行。繪製不同變量的概率分佈

dim(ret) 
[1] 208 3 

我對不同的變量一個接一個地做情節。

hist(ret$AAPL,breaks 
    freq=F, 
    main="The probaility distribution of AAPL", 
    xlab="AAPL") 
hist(ret$GOOGL,breaks 
    freq=F, 
    main="The probaility distribution of GOOGL", 
    xlab="GOOGL") 
hist(ret$WMT,breaks 
    freq=F, 
    main="The probaility distribution of WMT", 
    xlab="WMT") 

現在,我嘗試使用sapply函數在一次中分別繪製變量。

但是,「main =」x「」和「xlab = x」的概率分佈不起作用。我嘗試將這些colnames放在x中。

另外,我也試着把這條線和變量放在一起。我使用的功能是

lines(density(,main="",lty=1,lwd=1) 

如果我和變量分別繪製,我做

hist(ret$AAPL,breaks 
    freq=F, 
    main="the probaility distribution of AAPL", 
    xlab="AAPL") 
lines(density(ret$AAPL),main="AAPL",lty=1,lwd=1) 

但如何使用sapply功能做起來呢? 有人可以請告訴我如何解決問題: 使用sapply函數繪製概率分佈與不同變量的概率密度線。

回答

0

我會爲這個任務使用一些quantmod和ggplot2包。如果您的問題確實是特定於histsapply,請忽略此。

library(ggplot2) # to access round_any 
library(quantmod) 

getSymbols(c("AAPL","GOOGL","WMT")) 

A=data.frame('aapl',AAPL$AAPL.Close) 
G=data.frame('goog',GOOGL$GOOGL.Close) 
M=data.frame('wmt',WMT$WMT.Close) 
names(A)=names(G)=names(M)=c('symbol','close') 
d=rbind(A,G,M) 

m <- ggplot(d, aes(x=close, colour=symbol, group=symbol)) 
m + geom_density(fill=NA) 

enter image description here

,或者如果你想有一個直方圖

m <- ggplot(d, aes(x=close, colour=symbol, group=symbol)) 
m + geom_histogram(fill=NA,position='dodge') 

enter image description here

0

像這樣的事情?我假設你的data.frame ret有回報,而不是價格,但基本的方法應該在任何情況下都有效。

# set up example - you have this already... 
library(quantmod) # for getSymbols 
symbols <- c("AAPL", "GOOG", "WMT") 
ret  <- do.call(merge,lapply(symbols,function(s)dailyReturn(Cl(getSymbols(s,src="google",auto.assign=FALSE))))) 
names(ret) <- symbols 
ret  <- data.frame(date=index(ret), ret) 
# you start here... 
plot.hist <- function(x,s) { 
    hist(x,breaks=100,freq=F,xlab=s,main=paste("Histogram of",s), xlim=0.1*c(-1,1)) 
    lines(density(x, na.rm=TRUE),lty=1,lwd=1) 
} 
par(mfrow=c(3,1)) 
mapply(plot.hist, ret[,2:4], symbols) 

這裏有一些細微差別。

首先,您需要標題中的股票代碼,而不是字符串「x」。要做到這一點,你需要使用paste(...)如上。

其次,在使用sapply(...)時,data.frame的列確實被傳遞給該函數,但是的列名沒有。所以我們必須通過這兩個。最簡單的方法是使用mapply(...)(閱讀文檔)。

最後,在對方的回答中指出,你的確可以使用ggplot對於這一點,這也是我建議:

library(ggplot2) 
library(reshape2) # for melt(...) 
gg.df <- melt(ret, id="date", variable.name="Stock", value.name="Return") 
ggplot(gg.df, aes(x=Return))+ 
    geom_histogram(aes(y=..density.., fill=Stock),color="grey80",binwidth=0.005)+ 
    stat_density(geom="line")+ 
    facet_grid(Stock~.)