Fiz uma série temporal que tem um eixo x descontínuo, porém, só sei fazer esse tipo de gráfico quando o eixo x Date
é um fator. O problema que isso causa é que os pontos no gráfico se alinham com o fator que sugere que os pontos são coletados no primeiro dia do mês, o que não é verdade. Existe alguma maneira de alinhar os pontos com o real, Date
mantendo o eixo x descontínuo?
Exemplo
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)
Criado em 04/04/2024 com reprex v2.0.2
Você poderia fazer isso
facet_grid(scales = "free_x", space = "free_x")
para que os pontos fiquem proporcionalmente espaçados entre as facetas.Alternativamente, poderíamos converter as datas para ajuste numérico +, que se já tivermos estabelecido um eixo x discreto (com uma camada transparente como a existente), será colocado nele: