gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:58:42 26 4
gpt4 key购买 nike

我正在尝试按周和月绘制时间序列数据;理想情况下,我想,我想使用箱线图来可视化按周划分的每日数据。虽然我可以使用 scale_x_date 更改 x 轴上的标签和网格线,这不会影响图中的点。

这是问题的演示和我当前的(笨拙的)解决方案。

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...

我确信在 ggplot 中有一种更优雅的方法可以做到这一点。 .我对吗?

@shadow 在下面的回答要简洁得多。但是有没有办法使用分箱来做到这一点?使用 stats以某种形式,也许?

最佳答案

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

  • 此外,我发现创建一个名为“Month”的新变量因子来按月对箱线图进行分组更容易。在这种情况下,我使用 lubridate 来完成任务。
  • 如果您不想经历创建新变量“Month”的麻烦,您的 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")

  • enter image description here

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

    enter image description here

    关于r - ggplot2:按月和周绘制时间序列数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19226523/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com