我在研究ggplot代码。我有一个tsible格式的数据集AirPassenger
,我想创建一个分面网格图,其中包含四个线图,显示观察到的数据、趋势、季节和不规则的分量。我已经设法使用以下代码创建了绘图:
library(fpp3)
library(tsibble)
library(ggplot2)
library(scales)
library(zoo)
# Load the data
pr1<-AirPassengers
# Convert time series to tsibble format
pr1_tsibble <- as_tsibble(pr1)
# Apply X-13ARIMA-SEATS model and perform decomposition
fit <- pr1_tsibble %>%
model(X_13ARIMA_SEATS(value ~ transform(`function` = "none") + x11(mode = "add"))) %>%
components()
# Extract components
index <- pr1_tsibble$index
data <- pr1_tsibble$value
trend <- fit$trend
seasonal <- fit$seasonal
irregular <- fit$irregular
# Combine components with the original data
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 = "Observed")) +
geom_line(aes(y = trend, color = "Trend"))+
geom_line(aes(y = seasonal, color = "Seasonal")) +
geom_line(aes(y = irregular, color = "Irregular"))+
xlab('') + ylab("") +
theme_light() +
scale_color_manual(
values = c("Observed" = "grey", "Trend" = "black", "Seasonal" = "green", "Irregular" = "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"))
它生成了图:
我在X轴标签中所期望的..
当前的图几乎是我所需要的,但我希望线图跨越刻面网格连接。目前,每个线图在年份之间都是断开的。我如何修改代码以在facet网格上实现连续的geom_line?
任何帮助或建议将不胜感激!
2条答案
按热度按时间zdwk9cvp1#
伪造没有面的标签:
z8dt9xmd2#
你可以通过在x轴上设置
expand = c(0, 0)
来实现这一点。您需要复制上一年1月1日至12月31日的值,以确保行是连续的。虽然这可能感觉有点像作弊,但请记住,每个方面的像素远远少于365,所以这不会影响情节的外观: