Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

r - Shade alternate quarters using ggplot2 and also alternate methods

I want to create vertical bands for a line chart using ggplot2 or any other way in R.

    date <- seq.Date(from = as.Date("2015/01/01"), to = as.Date("2018/01/01"), by = 1)
    data <- runif(1097)
    
    df <- data.frame(cbind(date,data))
    df$date <- as.Date(df$date)
    
    datebreaks <- seq(as.Date("2015/01/01"), as.Date("2018/01/01"), by = "3 month")
    
    
    ggplot(df, aes(x = date, y = data)) + 
        geom_line() + ylim(-1,2) +
        scale_x_date(breaks = datebreaks)

gives this enter image description here

What I need is a chart with alternate quarters shaded.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There's no ggplot method for this that I know of, but you can generate the bars pretty easily and use geom_rect.

library(ggplot2)
library(dplyr)
library(lubridate)

df <- data.frame(
  date = seq.Date(from = as.Date("2015/01/01"), to = as.Date("2018/01/01"), by = 1),
  data = runif(1097)
)


datebreaks <- seq(as.Date("2015/01/01"), as.Date("2018/01/01"), by = "3 month")

# Generate bars
df_bars <- data.frame(
  xmin = seq(as.Date("2015/01/01"), as.Date("2017/07/01"), by = "6 months"),
  ymin = -Inf, ymax = Inf
) %>% 
  mutate(xmax = xmin + months(3))

ggplot(df) + 
  geom_rect(data = df_bars, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax),
            fill = '#55555555') +
  geom_line(aes(x = date, y = data)) + 
  scale_x_date(breaks = datebreaks, expand = c(0,0),
               labels = function(x) paste0(year(x), ' Q', quarter(x))) + 
  ylim(c(-1,2))

Time series with quarter bars

EDIT: I added a line formatting the x-axis


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...