繁体   English   中英

自定义 ggplot 上的 x 轴标签:仅显示星期一的日期

[英]Customize x-axis labels on ggplot: Only display dates that are on Mondays

我想更改 x 轴标签以显示星期一日期而不是每个月的 1 日和 15 日。 因此,对于此示例,我希望看到 6 月 7 日、6 月 14 日等。

在此处输入图片说明

df = structure(list(Date = structure(c(18779, 18780, 18781, 18782, 
18783, 18785, 18786, 18787, 18788, 18789, 18790, 18791, 18792, 
18793, 18794, 18795, 18796, 18799, 18800, 18801, 18802, 18803, 
18805, 18806, 18807, 18808, 18809, 18810, 18811, 18814, 18815, 
18816, 18817, 18819, 18820, 18821, 18822, 18823, 18824, 18825, 
18827, 18828), class = "Date"), Count = c(18L, 26L, 22L, 9L, 
1L, 10L, 17L, 19L, 15L, 11L, 1L, 1L, 11L, 21L, 25L, 24L, 9L, 
31L, 43L, 17L, 14L, 5L, 1L, 16L, 22L, 31L, 17L, 9L, 1L, 14L, 
9L, 15L, 11L, 1L, 29L, 38L, 39L, 24L, 8L, 1L, 11L, 20L)), row.names = c(NA, 
-42L), class = c("tbl_df", "tbl", "data.frame"))


ggplot(df, aes(x=Date, y=Count)) + geom_bar(stat="identity", fill="steelblue")

你可以试试

ggplot(df, aes(x=Date, y=Count)) + 
    geom_bar(stat="identity", fill="steelblue") + 
    scale_x_date(date_breaks = "week", date_labels = "%b %d")

在此处输入图片说明

您可以定义时间轴中断并定义要查看的标签(和子步骤)。

在您的情况下,日期步骤被明确定义为一系列星期一(也就是每 7 天)。 基础 R seq()理解时间单位。
如果需要,您可以定义任意日期, 如下所示

library(lubridate)  # for time processing

#-------- define time sequence
start_date <- lubridate::ymd("2021-05-31")
end_date   <- lubridate::ymd("2021-07-01")   # set this to your liking
date_seq   <- seq(from = start_date, to = end_date, by = "7 days")  # our vector of date labels

#--------- plot and add the time scale and it configuration
ggplot(df, aes(x=Date, y=Count)) + 
   geom_bar(stat="identity", fill="steelblue") + 

### ------------- set a date scale and "configure" to your liking

    scale_x_date(  breaks = date_seq     # setting user defined breaks
                   ,minor_breaks = "1 day"      # keep minor breaks evenly spaced
                   ,date_labels = "%d %b"       # show day and month
    )

这产生:

在此处输入图片说明

ggplot(df, aes(x=Date, y=Count)) + 
    geom_bar(stat="identity", fill="steelblue") +
    scale_x_date(date_breaks = 'week', 
                 date_labels = '%b %d\n%a')

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM