首页 > 解决方案 > 使用 ggplot 中的 facet_wrap 为时间序列复制 X 轴

问题描述

我希望你有一个美好的一天!所以,我有一个大约二十年的大型数据集,我正在尝试使用 facet_wrap 参数来可视化它。以下是用于故障排除的数据的简化版本:

data <- data.frame(
Date = c("1993-06-09", "1993-08-16", "1993-09-13", "1993-10-11", "1993-11-08", "1994-03-06", "1994-05-20", "1994-07-12", "1994-12-06", "1994-09-07", "1995-04-04", "1995-01-07", "1995-02-06"),
Oxygen = c("15", "15.8", "15.3", "16", "16", "14.5", "14.9", "15.2", "15.7", "15", "12.6", "12.8", "13.5"),
Year = c("1993", "1993", "1993", "1993", "1993", "1994", "1994", "1994", "1994", "1994", "1995", "1995", "1995"),
Month = c("6", "8", "9", "10", "11", "3", "5", "7", "12", "9", "4", "1", "2"),
Day = c("9", "16", "13", "11", "8", "6", "20", "12", "6", "7", "4", "7", "6")
)

这是它周围的其余代码:

data$Oxygen <- as.numeric(as.character(data$Oxygen))
data$Year <- as.numeric(as.character(data$Year))
data$Month <- as.numeric(as.character(data$Month))
data$Day <- as.numeric(as.character(data$Day))
data$Date <- as.Date(data$Date)
ggplot(data = data, aes(x=Date, y=Oxygen)) + geom_point() + geom_smooth(method = "loess", se=FALSE) + facet_wrap( ~ Year, ncol=2) + scale_x_date(date_breaks = "1 month", date_labels = "%B")  + theme(axis.text.x=element_text(angle = 90, hjust = 1)) +  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),panel.background = element_blank(), axis.line = element_line(colour = "black"))

代码创建此图:

图像

我的问题是x轴。如何更改它,使其不会为每年创建连续的几个月?我想要它,以便它适合一年的几个月,而不是创造更多的月份,就好像每年都不一样。

这就是我在余下的时间里的样子:

图像

它绘制的是每年的 x 轴,而不仅仅是一年的几个月。

最后,我如何告诉 ggplot 我想查看每个月内的一周或一天,以便并非所有点都集中在该月沿 x 轴的固定点上。

感谢您的时间!

标签: rggplot2time-seriesfacet-wrap

解决方案


为了获得一致的月休,您可以创建一个日期的虚拟变量,所有日期都具有相同的年份,并按实际年份分面。这样,您仍然在 x 轴上有一个日期,让您可以访问scale_x_date,但可以按年份整齐地拆分数据。

为了简洁和偏好,我使用 进行了清理dplyr,并制作了一个虚拟日期列,将年份更改为 2018,然后使用 转换为日期对象lubridate::ymd

library(tidyverse)
library(lubridate)

data2 <- data %>%
  mutate_at(vars(-Date), function(x) as.numeric(as.character(x))) %>%
  mutate(Date = as.Date(Date)) %>%
  mutate(dummy_date = paste("2018", Month, Day) %>% ymd())


ggplot(data2, aes(x = dummy_date, y = Oxygen, group = Year)) +
  geom_point() +
  geom_smooth(method = loess, se = FALSE) +
  scale_x_date(date_breaks = "1 month", date_labels = "%B") +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  facet_wrap(~ Year, ncol = 2)

reprex 包(v0.2.0)于 2018 年 6 月 25 日创建。


推荐阅读