如何在ggplot2中跨越时间序列数据中的facet边界创建连续的geom_line?

huangapple go评论65阅读模式
英文:

How to create a continuous geom_line across a facet boundaries in ggplot2 over the time series data?

问题

I can provide a translation of the code portion you provided without addressing your specific request for a plot. Here's the translated code:

我正在编写一个 ggplot 代码。我有一个以 tsibble 格式表示的数据集 `AirPassenger`,我想创建一个分面网格图,其中包括四个线图,显示观测数据、趋势、季节和不规则成分。我已经成功使用以下代码创建了这个图:

library(fpp3)
library(tsibble)
library(ggplot2)
library(scales)
library(zoo)

# 载入数据
pr1 <- AirPassengers

# 将时间序列转换为 tsibble 格式
pr1_tsibble <- as_tsibble(pr1)

# 应用 X-13ARIMA-SEATS 模型并执行分解
fit <- pr1_tsibble %>%
  model(X_13ARIMA_SEATS(value ~ transform(`function` = "none") + x11(mode = "add"))) %>%
  components()

# 提取各成分
index <- pr1_tsibble$index
data <- pr1_tsibble$value
trend <- fit$trend
seasonal <- fit$seasonal
irregular <- fit$irregular

# 将成分与原始数据合并
combined <- data.frame(index, data, trend, seasonal, irregular)

library(dplyr)
combined <- combined %>%
  mutate(year = as.factor(format(index, "%Y")))
combined$index <- as.Date(combined$index, format = "%Y%b")

ggplot(combined, aes(x = index)) +
  geom_line(aes(y = data, color = "观测值")) +
  geom_line(aes(y = trend, color = "趋势")) +
  geom_line(aes(y = seasonal, color = "季节")) +
  geom_line(aes(y = irregular, color = "不规则")) +
  xlab('') + ylab('') +
  theme_light() +
  scale_color_manual(
    values = c("观测值" = "grey", "趋势" = "black", "季节" = "green", "不规则" = "blue"),
    name = ''
  ) +
  scale_y_continuous(
    labels = function(x) format(x, nsmall = 2)
  ) +
  scale_x_date(labels = NULL, breaks = NULL, 
               date_minor_breaks = "1 month") + 
  facet_wrap(~year, nrow = 1, scales = 'free_x',
             strip.position = 'bottom') +
  theme(panel.spacing.x = unit(0, "lines"),
        panel.grid = element_blank(), 
        legend.position = "top",
        strip.background = element_rect(colour = "white", fill = "grey"))

Please note that this is just a translation of the code, and I haven't addressed the specific plot issue you mentioned.

英文:

I'm working on a ggplot code. I have a dataset AirPassenger in tsibble format and I want to create a facet grid plot with four line plots showing the observed data, trend, seasonal, and irregular components. I have managed to create the plot using the following code:

library(fpp3)
library(tsibble)
library(ggplot2)
library(scales)
library(zoo)
# Load the data
pr1&lt;-AirPassengers
# Convert time series to tsibble format
pr1_tsibble &lt;- as_tsibble(pr1)
# Apply X-13ARIMA-SEATS model and perform decomposition
fit &lt;- pr1_tsibble %&gt;%
model(X_13ARIMA_SEATS(value ~ transform(`function` = &quot;none&quot;) + x11(mode = &quot;add&quot;))) %&gt;%
components()
# Extract components
index &lt;- pr1_tsibble$index
data &lt;- pr1_tsibble$value
trend &lt;- fit$trend
seasonal &lt;- fit$seasonal
irregular &lt;- fit$irregular
# Combine components with the original data
combined &lt;- data.frame(index, data, trend, seasonal, irregular)
library(dplyr)
combined &lt;- combined %&gt;%
mutate(year = as.factor(format(index, &quot;%Y&quot;)))
combined$index&lt;-as.Date(combined$index, format= &quot;%Y%b&quot;)
ggplot(combined, aes(x = index)) +
geom_line(aes(y = data, color = &quot;Observed&quot;)) +
geom_line(aes(y = trend, color = &quot;Trend&quot;))+
geom_line(aes(y = seasonal, color = &quot;Seasonal&quot;)) +
geom_line(aes(y = irregular, color = &quot;Irregular&quot;))+
xlab(&#39;&#39;) + ylab(&quot;&quot;) +
theme_light() +
scale_color_manual(
values = c(&quot;Observed&quot; = &quot;grey&quot;, &quot;Trend&quot; = &quot;black&quot;, &quot;Seasonal&quot; = &quot;green&quot;, &quot;Irregular&quot; = &quot;blue&quot;),
name = &quot;&quot;
) +
scale_y_continuous(
labels = function(x) format(x, nsmall = 2)
)+
scale_x_date(labels = NULL, breaks = NULL, 
date_minor_breaks = &quot;1 month&quot;) + 
facet_wrap(~year, nrow=1, scales= &#39;free_x&#39;,
strip.position = &#39;bottom&#39;)+
theme(panel.spacing.x = unit(0, &quot;lines&quot;),
panel.grid = element_blank(), 
legend.position = &quot;top&quot;,
strip.background = element_rect(colour = &quot;white&quot;, fill = &quot;grey&quot;))

It produces the plot :

如何在ggplot2中跨越时间序列数据中的facet边界创建连续的geom_line?

What I am expecting in x-axis labelling ..
如何在ggplot2中跨越时间序列数据中的facet边界创建连续的geom_line?

The current plot is almost what I need, but I want the line plots to be connected across the facet grid. Currently, each line plot is disconnected between years. How can I modify the code to achieve a continuous geom_line across the facet grid?

Any help or suggestions would be greatly appreciated!

答案1

得分: 2

geom_vline(xintercept = yrs, alpha = 0.2) +
annotate("rect", xmin = yrs[1:(length(yrs)-1)],
xmax = yrs[2:length(yrs)], ymin = -150, ymax = -100,
fill = "gray90", color = "gray70") +
annotate("text", x = yrs[1:(length(yrs)-1)] + 182, label = 1949:1960,
y = -125) +

英文:

Faking the labels without facets:

geom_vline(xintercept = yrs, alpha = 0.2) +
annotate(&quot;rect&quot;, xmin = yrs[1:(length(yrs)-1)],
xmax = yrs[2:length(yrs)], ymin = -150, ymax = -100,
fill = &quot;gray90&quot;, color = &quot;gray70&quot;) +
annotate(&quot;text&quot;, x = yrs[1:(length(yrs)-1)] + 182, label = 1949:1960,
y = -125) +

如何在ggplot2中跨越时间序列数据中的facet边界创建连续的geom_line?

答案2

得分: 2

你可以通过在x轴上设置expand = c(0, 0)来使用facets来实现这个目标。您需要将1月1日的值复制到前一年的12月31日,以确保曲线连续。虽然这可能有点像作弊,但请记住,每个facet上的像素远少于365个,所以这不会影响图表的外观:

combined %>%
  filter(lubridate::month(index) == 1) %>%
  mutate(index = index - 1, 
         year = factor(as.numeric(as.character(year)) - 1)) %>%
  bind_rows(combined) %>%
  filter(year != "1948") %>%
  ggplot(aes(x = index)) +
  geom_line(aes(y = data, color = "Observed")) +
  geom_line(aes(y = trend, color = "Trend"))+
  geom_line(aes(y = seasonal, color = "Seasonal")) +
  geom_line(aes(y = irregular, color = "Irregular"))+
  labs(x = NULL, y = NULL) +
  theme_light() +
  scale_color_manual(NULL,
    values = c("Observed" = "grey", "Trend" = "black", 
               "Seasonal" = "green", "Irregular" = "blue")) +
  scale_y_continuous(labels = ~format(.x, nsmall = 2)) +
  scale_x_date(labels = NULL, breaks = NULL, expand = c(0, 0),
               date_minor_breaks = "1 month") + 
  facet_wrap(~year, nrow = 1, scales= 'free_x',
             strip.position = 'bottom') +
  theme(panel.spacing.x = unit(0, "lines"),
        panel.grid = element_blank(), 
        legend.position = "top",
        strip.background = element_rect(colour = "white", fill = "grey"))

如何在ggplot2中跨越时间序列数据中的facet边界创建连续的geom_line?


<details>
<summary>英文:</summary>
You _can_ do this with facets by setting `expand = c(0, 0)` in your x axis. You will need to copy over the 1st of January values to 31st December the previous year to ensure the lines are continuous. Although this may feel a bit like cheating, remember that there are far fewer than 365 pixels across each facet, so this will not effect the look of the plot:
```r
combined %&gt;%
filter(lubridate::month(index) == 1) %&gt;%
mutate(index = index - 1, 
year = factor(as.numeric(as.character(year)) - 1)) %&gt;%
bind_rows(combined) %&gt;%
filter(year != &quot;1948&quot;) %&gt;%
ggplot(aes(x = index)) +
geom_line(aes(y = data, color = &quot;Observed&quot;)) +
geom_line(aes(y = trend, color = &quot;Trend&quot;))+
geom_line(aes(y = seasonal, color = &quot;Seasonal&quot;)) +
geom_line(aes(y = irregular, color = &quot;Irregular&quot;))+
labs(x = NULL, y = NULL) +
theme_light() +
scale_color_manual(NULL,
values = c(&quot;Observed&quot; = &quot;grey&quot;, &quot;Trend&quot; = &quot;black&quot;, 
&quot;Seasonal&quot; = &quot;green&quot;, &quot;Irregular&quot; = &quot;blue&quot;)) +
scale_y_continuous(labels = ~format(.x, nsmall = 2)) +
scale_x_date(labels = NULL, breaks = NULL, expand = c(0, 0),
date_minor_breaks = &quot;1 month&quot;) + 
facet_wrap(~year, nrow = 1, scales= &#39;free_x&#39;,
strip.position = &#39;bottom&#39;) +
theme(panel.spacing.x = unit(0, &quot;lines&quot;),
panel.grid = element_blank(), 
legend.position = &quot;top&quot;,
strip.background = element_rect(colour = &quot;white&quot;, fill = &quot;grey&quot;))

如何在ggplot2中跨越时间序列数据中的facet边界创建连续的geom_line?

huangapple
  • 本文由 发表于 2023年6月5日 01:57:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76401727.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定