【问题标题】:Shade background of ggplot according to month根据月份对ggplot的背景进行着色
【发布时间】:2015-10-09 05:44:27
【问题描述】:

这段代码:

df <- data.frame(day <- 0:365, value = 1)
library(ggplot2)
ggplot(df, aes(day, value)) + geom_blank() + scale_x_continuous(breaks = seq(0, 365, 10)) + theme_bw()

产生这个情节:

使用 R 代码,我想根据 day 属于哪个月份来对绘图的背景进行着色。我希望情节如下所示(情节背景是 Photoshopped)。我会对使用 lubridate 的解决方案特别感兴趣。

【问题讨论】:

    标签: r date ggplot2 data-visualization lubridate


    【解决方案1】:

    这是使用geom_raster 的部分解决方案。

    library(lubridate)
    library(ggplot2)
    
    x <- seq(from = as.Date("2000/1/1"), to = as.Date("2000/12/31"), "day")
    xy <- data.frame(datum = x, day = day(x), month = month(x), seq.day = 1:length(x), 
                     month.ind = rep(rep(0:1, 6), times = rle(xy$month)$lengths))
    
    ggplot(xy, aes(x = seq.day, y = 1, fill = as.factor(month.ind))) +
      theme_bw() +
      scale_fill_manual(values = c("black", "white")) +
      scale_x_continuous(breaks = seq(0, 365, 10)) +
      geom_raster(alpha = 0.3, show_guide = FALSE)
    

    【讨论】:

    • 看来是时候买个更宽的屏幕了... :)
    【解决方案2】:

    可能不是最优的,但我认为它对你有用:

    df <- data.frame(day = 1:365, value = 1)
    #do some data manipulation. Calculate as date
    df$date <- as.Date(df$day, origin="2014-12-31")
    str(df)
    
    df$month <- month(df$date)
    df$month_name <- month(df$date,label=T)
    #calculate color 
    df$month_color <- ifelse(df$month %% 2,"black","white")
    
    #make plot using geom_bar and scale_fill/colour_identity()
    plot2 <- ggplot(df, aes(x=day, y=value)) + 
      geom_bar(stat="identity",aes(fill=month_color,color=month_color))+
      scale_fill_identity() +
      scale_color_identity() +
      scale_x_continuous(breaks = seq(0, 365, 10)) +
      theme_bw() +
      theme(panel.grid=element_blank())
    
    #make data for plotting months as geom_txt
    month_df <- do.call(rbind,lapply(split(df,df$month_name),function(x){
      return(x[1,])
    }))
    month_df
    
    plot2 + geom_text(data=month_df, aes(x=day+15, y=value-0.05, label=month_name),color="red")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-19
      • 1970-01-01
      • 1970-01-01
      • 2020-02-29
      • 1970-01-01
      • 1970-01-01
      • 2021-09-05
      • 1970-01-01
      相关资源
      最近更新 更多