我已经使用ggplot磁贴对热图进行了编码,并且在x轴上有连续的天数。我要解决的问题是从热图中删除周末,仅显示工作日。我发现一种解决方案是将日期转换为因子,但是如果这样做,如何将scale_x_discrete中的标签格式化为%d%m日期格式?有没有办法将日期保留为日期格式,而不是将其转换为因子?下面是一个示例:
randomString <- function(n=5,length=3) {
randomStringX <- c(1:n)
for(i in 1:n) {
randomStringX[i] <- paste(sample(c(LETTERS),length,replace = TRUE),collapse = "")
}
return(randomStringX)
}
randomString()
data.frame(client=randomString(),day=rep(seq.Date(Sys.Date()-10,length.out=10,by="1 day"),2)) %>% mutate(sales=round(rnorm(20,492,300),1)) %>% mutate(scale=cut(sales,breaks=c(0,100,200,300,max(sales)),labels = c("0-100","100-200","200-300","+300"))) %>% ggplot(.,aes(x=day,y=client,fill=scale)) + geom_tile() + scale_x_date(date_breaks = "1 day")
提前感谢
您可以使用is.weekend
中的chron
功能排除周末>
library(chron) library(dplyr) library(mutate) data.frame(client = randomString(), day = rep(seq.Date( Sys.Date() - 10, length.out = 10, by = "1 day"), 2)) %>% mutate(sales = round(rnorm(20, 492, 300), 1)) %>% mutate(scale = cut( sales, breaks = c(0, 100, 200, 300, max(sales)), labels = c("0-100", "100-200", "200-300", "+300") )) %>% filter(is.weekend(day) == FALSE) %>% #This line will remove weekends View() ggplot(., aes(x = day, y = client, fill = scale)) + geom_tile() + scale_x_date(date_breaks = "1 day")
这也可以使用
wday
中的lubridate
函数来完成,尽管我认为不太干净。