我制作了一个具有不连续 x 轴的时间序列,但是,我只知道当 x 轴是一个因素时如何制作此类图Date
。这导致的问题是,图中的点与表明这些点是在当月第一天收集的因素一致,但事实并非如此。有什么方法可以使点与实际对齐,Date
同时保持 x 轴不连续?
例子
library(tidyverse)
library(grid)
set.seed(333)
# Create example dataset
df <- data.frame(
Group = c('A','A','A','A','A','A','B','B','B','B','B','B'),
Date = rep(c('2021-07-13','2021-08-22','2021-09-04','2022-06-20','2022-07-08','2022-08-25'), 2),
Value = round(rnorm(12,50,20)))
# Do some data wrangling
df <- df %>%
mutate(Date = as.Date(Date),
year = year(Date),
mon = month(Date),
mon_abb = month.abb[mon],
monYear = paste(mon_abb,year, sep = ' ')) %>%
select(!c(mon,year,mon_abb))
# Will need the month abbreviation
sample_dates <- unique(df$monYear)
# Make figure
# Note: the points align on the month but I would like them to
# align with the actual calendar Date (i.e., all points would move
# to the right because none were collected on the 1st of the month)
ggplot(data = df, aes(x = factor(Date), y = Value, group = Group)) +
geom_point(aes(fill = Group), size = 3, shape = 21, color = "black") +
scale_x_discrete(labels = substr(sample_dates, 1, 3)) + # Pulls the month abb. for x-axis label
xlab("") +
theme_bw() +
theme(plot.margin = unit(c(1, 1, 2, 1), "lines"),
axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1),
legend.position = 'right',
panel.border = element_blank()) +
guides(fill = guide_legend(nrow = 2)) +
coord_cartesian(clip = 'off', ylim = c(0, 100)) +
annotation_custom(rectGrob(gp = gpar(fill = NA))) +
annotate(geom = "text", x = 2, y = -16, label = 2021, size = 4.5) +
annotate(geom = "text", x = 5, y = -16, label = 2022, size = 4.5) +
annotate(geom = 'rect', xmin = 3.4, xmax = 3.6, ymin = -10, ymax = -3, fill = 'white') +
annotate(geom = 'segment', x = c(3.4,3.6), xend = c(3.4,3.6), y = -8, yend = -3)
创建于 2024-04-04,使用reprex v2.0.2
您可以这样做,
facet_grid(scales = "free_x", space = "free_x")
以便点在各个面上按比例间隔。或者,我们可以将日期转换为数字+调整,如果我们已经建立了一个离散的x轴(具有像您现有的透明层一样的透明层),则该调整将被放置在该轴上: