You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用ggplot2绘制同画布双ACF图?附原有R基础绘图代码

Got it! The problem with using geom_area here is that it’s built for filled area plots, but your original base R ACF plot uses discrete vertical lines with tiny horizontal caps at the top. To recreate that stacked ACF look in ggplot2, we need to first grab the raw ACF data (instead of plotting directly), combine it into a tidy data frame, then use line segments to mimic the base R style.

Step 1: Calculate ACF data (skip direct plotting)

First, we’ll compute the ACF values for both datasets without generating the plot—this lets us work with the underlying numbers:

data1 <- seq(1, 3000, 3)
data2 <- seq(1, 1000, 0.5)

# Compute ACF and store results as objects (not plots)
acf_data1 <- acf(data1, plot = FALSE, lag.max = 300)
acf_data2 <- acf(data2, plot = FALSE, lag.max = 300)

Step 2: Combine into a tidy data frame

ggplot2 thrives on tidy data, so we’ll convert each ACF result into a structured tibble and bind them together with a grouping variable to distinguish the two datasets:

library(tibble)
library(dplyr)

# Convert ACF objects to tibbles and merge
tidy_acf <- bind_rows(
  tibble(lag = acf_data1$lag[, 1, 1], 
         acf_value = acf_data1$acf[, 1, 1], 
         dataset = "data1"),
  tibble(lag = acf_data2$lag[, 1, 1], 
         acf_value = acf_data2$acf[, 1, 1], 
         dataset = "data2")
)

Step 3: Plot with ggplot2 (match base R style)

We’ll use geom_segment to replicate the vertical lines and top caps from your original plot, then layer both datasets on the same axes:

library(ggplot2)

ggplot(tidy_acf, aes(x = lag, y = acf_value, color = dataset)) +
  # Vertical line from y=0 to the ACF value
  geom_segment(aes(xend = lag, yend = 0), size = 0.7) +
  # Small horizontal cap at the top of each line (matches base R's look)
  geom_segment(aes(xend = lag - 0.2, yend = acf_value)) +
  geom_segment(aes(xend = lag + 0.2, yend = acf_value)) +
  # Match your original color scheme (black for data1, red for data2)
  scale_color_manual(values = c("data1" = "black", "data2" = "red")) +
  # Keep the same y-axis limit as your base R plot
  ylim(0, 1) +
  # Add labels and tweak theme to mimic base R
  labs(x = "Lag", y = "Autocorrelation") +
  theme_classic() +
  theme(
    panel.grid.major.x = element_blank(),
    legend.position = "top" # Optional: adjust legend position if needed
  )

Why geom_area didn’t work

geom_area is designed to fill the area under a continuous line, which doesn’t align with the discrete vertical line style of the base R ACF plot. Using geom_segment lets us replicate the exact visual of your original plot while retaining ggplot2’s flexibility.

内容的提问来源于stack exchange,提问作者Xia.Song

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:57:43