每月以及图表上每月选定日期的日期标签 (ggplot)

问题描述 投票:0回答:2

我正在准备一个基本上如下所示的图表

df1 <- read.table(text = "DT   odczyt.1 odczyt.2
'2023-01-18 00:00:00'   686 1.5
'2023-02-18 23:00:00'   487 6.8
'2023-03-04 00:00:00'   498 1.5
'2023-04-20 03:00:00'   961 1.54
'2023-06-21 05:00:00'   397 1.6
'2023-08-10 19:00:00'   532 6.6
'2023-08-21 23:00:00'   493 3.8
'2023-09-19 01:00:00'   441 9.2
'2023-11-3 07:00:00'    793 8.5
'2023-12-21 13:00:00'   395 5.5", header = TRUE) %>% 
  mutate (DT = as.POSIXct(DT))

ggplot (df1) +
  geom_line(aes (x = DT, y = odczyt.1), color = "indianred") +
  scale_x_datetime(breaks = "1 month",
                   minor_breaks = "2 day") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5),
        legend.position = "top",
        legend.justification = "center") 

我想在 x 轴上为该月的每个 10 号添加标签。有一个简单的方法吗?当然,我希望保留图表的其余元素。

r ggplot2
2个回答
0
投票

您可以创建数据涵盖的每个月 10 日的 POSIXct 项目向量,然后在

breaks =
参数中使用它。

# create the dates for the labels
my_dates <- do.call(
    make_datetime,
    setNames(
        crossing(year(min(df1$DT)):year(max(df1$DT)), 1:12, 10),
        c("year", "month", "day")
    )
)

# use this vector in breaks= parameter
ggplot (df1) +
  geom_line(aes (x = DT, y = odczyt.1), color = "indianred") +
  scale_x_datetime(breaks =my_dates,
                   minor_breaks = "2 day") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5),
        legend.position = "top",
        legend.justification = "center") 

您可能需要过滤标签向量,因为它针对每年的数据从 1 月到 12 月运行。如果您从六月到六月绘制图表,则会创建额外的标签。


0
投票

您可以创建日期时间向量来自定义轴标签

library(tidyverse)

breaks <- as_datetime(c(seq(ymd_h('2023-01-01 12'), ymd_h('2024-01-01 12'), by = '1 month'),
                        seq(ymd_h('2023-01-01 12'), ymd_h('2024-01-01 12'), by = '1 month') + days(x = 9)))

ggplot (df1) +
  geom_line(aes (x = DT, y = odczyt.1), color = "indianred") +
  scale_x_datetime(breaks = breaks, date_labels = '%Y-%m-%d',
                   date_minor_breaks = '2 days') +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5),
        legend.position = "top",
        legend.justification = "center") 

创建于 2024-04-27,使用 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.