Shade background of ggplot according to month

南楼画角 提交于 2019-12-10 18:58:41

问题


This code:

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()

Produces this plot:

Using R code, I want to shade the background of the plot according to which day falls in which month. I want the plot to look like below (the plot background is Photoshopped). I would be particularly interested in a solution that uses lubridate.


回答1:


Here's part of the solution using 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:


Probably not optimal, but I think it will work for you:

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")



来源:https://stackoverflow.com/questions/31510796/shade-background-of-ggplot-according-to-month

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!