Looking for a way to condition/adjust the color of the background facet_grid
. Can't find examples anywhere that use a variable/column in the panel.background = element_rect(fill =
option of ggplot. MnWE below, which shows the idea I am going after, where July and August grids should have no grey paneling behind them, but June (and all other months) should. Not looking for a solution that uses the drop=TRUE
option in facet_grid
.
library(tidyquant)
library(plyr)
library(plotly)
amznStock = as.data.frame(tidyquant::tq_get(c("AMZN"),get="stock.prices")) # get data using tidyquant
amznStock = amznStock[year(amznStock$date) > 2012, ] # Using data only after 2012Using ggplot2
amznStock$weekday = as.POSIXlt(amznStock$date)$wday #finding the day no. of the week
amznStock$weekdayf<-factor(amznStock$weekday,levels=rev(1:7),labels=rev(c("Mon","Tue","Wed","Thu","Fri","Sat","Sun")),ordered=TRUE) #converting the day no. to factor
amznStock$monthf<-factor(month(amznStock$date),levels=as.character(1:12),labels=c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"),ordered=TRUE) # finding the month
amznStock$yearmonth<- factor(as.yearmon(amznStock$date)) #finding the year and the month from the date. Eg: Nov 2018
amznStock$week <- as.numeric(format(amznStock$date,"%W")) #finding the week of the year for each date
amznStock<-ddply(amznStock,.(yearmonth),transform,monthweek=1+week-min(week)) #normalizing the week to start at 1 for every month
#pretend we are missing data for june
amznStock<-amznStock[amznStock$monthf!="Jun",]
#pretend there are no data for jul or aug
amznStock<-amznStock[amznStock$monthf!="Jul",]
amznStock<-amznStock[amznStock$monthf!="Aug",]
p <- ggplot(amznStock, aes(monthweek, weekdayf, fill = amznStock$adjusted)) + geom_tile(colour = "white") + facet_grid(year(amznStock$date)~monthf, drop=FALSE) + scale_fill_gradient(low="red", high="green") + xlab("Week of Month") + ylab("") + ggtitle("Time-Series Calendar Heatmap: AMZN Stock Prices") + labs(fill = "Price")
p
#set intended grid coloring
x2$background<-"light grey"
#turn off facet grid color when (pretending) there are no data for july or aug
x2$background[x2$monthf=="Jul"]<-"white"
x2$background[x2$monthf=="Aug"]<-"white"
p2<- p +
theme(
panel.background = element_rect(fill = x2$background),
)
p2