【问题标题】:Customize x-axis labels on ggplot: Only display dates that are on Mondays自定义 ggplot 上的 x 轴标签:仅显示星期一的日期
【发布时间】:2021-07-29 02:27:29
【问题描述】:

我想更改 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")

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    你可以试试

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

    【讨论】:

      【解决方案2】:

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

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

      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
          )
      

      这会产生:

      【讨论】:

        【解决方案3】:
        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')
        
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-09-29
          • 2014-02-14
          • 1970-01-01
          • 2023-04-05
          • 1970-01-01
          • 1970-01-01
          • 2020-02-05
          • 2020-06-06
          相关资源
          最近更新 更多