ggplot2:按月和周绘制时间序列数据

med*_*zar 6 r ggplot2

我试图按周和月绘制时间序列数据; 理想情况下,我认为,我想使用箱形图来显示按周分类的每日数据.虽然我可以使用更改x轴上的标签和网格线scale_x_date,但这不会影响绘图中的点.

这是一个问题的演示和我目前(笨拙)的解决方案.

library(zoo)
library(ggplot2)

d = as.Date(c(as.Date("2007-06-01"):as.Date("2008-05-31"))) # using zoo to reformat numeric 
x = runif(366, min = 0, max = 100)
df = data.frame(d,x)

# PROBLEM #    
p = ggplot(df, aes(d, x))
p + geom_point()
p + geom_boxplot() # more or less useless

# CURRENT FIX #
df$Year.Month <- format(df$d, "%Y-%m")
p = ggplot(df, aes(Year.Month, x))
p + geom_point(alpha = 0.75)
p + geom_boxplot() # where I'm trying to get to...
Run Code Online (Sandbox Code Playgroud)

我确信从内部有更优雅的方式来做到这一点ggplot.我对吗?

@ shadow的答案下面更整洁.但有没有办法使用binning来做到这一点?stats或许以某种形式使用?

Dan*_*Dan 2

您可以将日期视为 R 中的日期,并使用 ggplot 中的scale_x_date() 来获取所需的x 标签。

  • 另外,我发现创建一个名为“月”的新变量因子来按月对箱线图进行分组更容易。在本例中,我使用 lubridate 来完成任务。

  • 如果您不想经历创建新变量“月份”的麻烦,则您的 bloxplot 将在该月的 15 日绘制,这使得可视化阅读变得更加困难。

    library(magrittr)
    library(lubridate)
    library(dplyr)
    
    df %>%
      mutate(Date2 = as.Date(paste0("2000-", month(d), "-", "01"))) %>%
      mutate(Month = lubridate::month(d)) %>%
    
    ggplot(aes(Date2, x, group=Month)) +
      geom_boxplot() +
      scale_x_date(date_breaks="1 month", date_labels = "%b")
    
    Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

如果您不创建变量“Month”,箱线图将无法与 x 刻度线很好地对齐:

在此输入图像描述