使用ggplot2绘制ACF图:设置geom_bar的宽度

MYa*_*208 17 r ggplot2

随着acf我们可以ACF plot在基地R图.

x <- lh
acf(x)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

下面的代码可以用来获取ACF plotggplot2.

conf.level <- 0.95
ciline <- qnorm((1 - conf.level)/2)/sqrt(length(x))
bacf <- acf(x, plot = FALSE)
bacfdf <- with(bacf, data.frame(lag, acf))

library(ggplot2)
q <- ggplot(data=bacfdf, mapping=aes(x=lag, y=acf)) +
       geom_bar(stat = "identity", position = "identity")
q
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

如何获得线而不是条形或如何设置条的宽度,使它们看起来像线条?谢谢

Rei*_*son 21

您可能最好通过线段绘制线条 geom_segment()

library(ggplot2)

set.seed(123)
x <- arima.sim(n = 200, model = list(ar = 0.6))

bacf <- acf(x, plot = FALSE)
bacfdf <- with(bacf, data.frame(lag, acf))

q <- ggplot(data = bacfdf, mapping = aes(x = lag, y = acf)) +
       geom_hline(aes(yintercept = 0)) +
       geom_segment(mapping = aes(xend = lag, yend = 0))
q
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 这个答案非常古老(并且仍然有用)。只是注意到你忘了添加`geom_hline(aes(yintercept = ciline), linetype = 3, color = 'darkblue') + geom_hline(aes(yintercept = -ciline), linetype = 3, color = 'darkblue')`模仿原始底图中的线条 (2认同)

sha*_*dow 5

如何使用width = 0的geom_errorbar?

ggplot(data=bacfdf, aes(x=lag, y=acf)) + 
    geom_errorbar(aes(x=lag, ymax=acf, ymin=0), width=0)
Run Code Online (Sandbox Code Playgroud)