【问题标题】:How to customize and add discrete time steps to x-axis in time series plot in ggplot2 in R?如何在 R 中 ggplot2 的时间序列图中自定义离散时间步并将其添加到 x 轴?
【发布时间】:2020-04-10 18:02:00
【问题描述】:

我正在努力在 ggplot 的 x 轴上获取日期字段。我正在使用的数据是来自两个不同传感器的气溶胶浓度的时间序列数据。时间序列中的日期字段不是连续的。相反,它包含一年中仅三个月的每日观察,即从 2007 年到 2016 年的 3 月、4 月和 5 月。因此,当我将数据框中的日期列分配为“日期”字段时,它显示了这一点图中我不喜欢的链接。 ggplot output。但是,如果没有将日期列指定为“日期”,它会显示这个数字。 ggplot output2。这个新图形的问题是 x 轴文本的不可读性。我想,这背后的原因是 - 日期字段已被读取为因子变量。通过对代码进行一些修改,我可以删除 x 轴刻度和轴文本。现在我希望将数据框中的原始日期放在 x 轴上,并有合理的休息时间。我正在分享我使用过的代码和data 的一个子集。

library(ggplot2)
library(reshape2)
df = read.csv('./mydata.csv')
names(df) = c('Date','MODIS','MISR')
df_melt = melt(df, id.vars = 'Date')
head(df_melt)
names(df_melt) = c('Date','grp','AOD')
ggplot(df_melt, aes(x = Date, y = AOD, group = 1, colour = grp))+
  theme(axis.text.x = element_blank()
        ,axis.ticks.x = element_blank())+
  geom_line()+
  facet_wrap(~ grp, ncol = 1)

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    计算起来确实有点麻烦。我的建议是使用游程编码来查找年/月的第一次出现并将其用作轴中断。

    # Loading your data
    df <- read.csv(file.choose())
    df <- setNames(df, c("Date", "MODIS", "MISR"))
    
    # Convert dates to ordered factors (totally assumes dates are in correct order)
    df$Date <- ordered(as.character(df$Date), levels = as.character(df$Date))
    
    # Find appropriate breaks
    char_date <- as.character(df$Date)
    nch <- nchar(char_date)
    
    ## Find which factor level is the first of a new year
    years <- rle(substr(char_date, nch - 3, nch))
    year_breaks <- cumsum(years$lengths) - years$lengths + 1
    
    ## Find which factor level is the first day of a new month
    months <- rle(substr(char_date, 4, 5))
    month_breaks <- cumsum(months$lengths) - months$lengths + 1
    
    # Melt data
    df_melt <- reshape2::melt(df, id.vars = 'Date')
    names(df_melt) = c('Date','grp','AOD')
    
    # Use date as numeric
    ggplot(df_melt, aes(x = as.numeric(Date), y = AOD, group = 1, colour = grp))+
      geom_line()+
      scale_x_continuous(breaks = year_breaks, labels = years$values,
                         minor_breaks = month_breaks) +
      facet_wrap(~ grp, ncol = 1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-20
      • 1970-01-01
      相关资源
      最近更新 更多