2016-02-26 33 views
0

我想在R中使用ggplot繪製2個ACFs。我使用geom_segment(),它工作正常,但有一點煩人的細節是,根據我聲明geom_segment的順序,如果我在最大值之前聲明它們,圖形會覆蓋最小的ACF。如果一個ACF總是有一個更大的值,那麼這就不成問題了(以前我會用geom_segment的情況)。我知道這聽起來有點混亂,所以這裏是一個工作示例:繪製2個ACFs ggplot2 - 顯示最小值顏色

library(ggplot2) 
library(grid) 
library(plyr) 

set.seed(123) 
data1 <- arima.sim(n = 10000, model = list(ar = 0.4,ma=0.4)) 
data2 <- arima.sim(n = 10000, model = list(ma = c(0.9,0.3))) 

acf1 <- acf(data1, plot = FALSE,lag.max=15) 
acf1DF <- with(acf1, data.frame(lag, acf)) 
acf1DF$lag <- as.integer(acf1DF$lag) 
acf2 <- acf(data2, plot = FALSE,lag.max=15) 
acf2DF <- with(acf2, data.frame(lag, acf)) 
acf2DF$lag <- as.integer(acf2DF$lag) 

q <- ggplot(data = acf1DF, mapping = aes(x = lag, y = acf)) + 
    geom_hline(aes(yintercept = 0)) + 
    geom_segment(mapping = aes(xend = lag, yend = 0,color="red")) + 
    geom_segment(data=acf2DF,mapping = aes(x=lag,y=acf,xend = lag, yend = 0), 
    inherit.aes=FALSE,show.legend=FALSE) 
q 

注意,我看不到的最小值爲先滯後。

謝謝。

回答

3

它會成爲您創建barplot的解決方案嗎?分段重疊的問題會使您的情節變得不那麼容易理解,可能會指向使用不同的可視化方案作爲解決方案。這裏是一個barplot:

首先,我們將數據結合在ggplot中,當你多次調用geom時,你沒有做正確的事情。

acf1DF$group <- 1 
acf2DF$group <- 2 

dat <- rbind(acf1DF,acf2DF) 

然後,我們可以做一個barplot:

p1 <- ggplot(dat,aes(x=factor(lag), y=acf,fill=factor(group))) + 
    geom_bar(width=0.3,stat="identity", position=position_dodge()) 

enter image description here 或者,如果我們真的要細分,而不是棒(例如,因爲我們希望有一個連續的x軸,或類似的外觀線作爲圖例),我們可以繪製

dat$lag_offset <- dat$lag + as.numeric(dat$group==2) * 0.1 

然後情節段之前添加輕微偏移組2滯後:

p2 <- ggplot(dat, aes(x=lag_offset, xend=lag_offset, y=0,yend=acf, color=factor(group))) + 
    geom_segment() + 
    scale_color_manual(values=c(`1`="black",`2`="red")) 

enter image description here

+0

非常感謝;我開始獲得ggplot數據安排的要點。 – user191919

+0

不客氣!我知道一次查看您的數據int格式是非常有用的。並且知道如何將數據轉換成形狀ggplot想要它(長時間,一行上的數據點的所有信息)將使您的ggplot生活更容易。 – Heroka