r语言 - 从热图的 X 轴中排除周末



我已经使用 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中排除周末的数据

可以使用bdscale包从 x 轴中排除周末日期本身

library(chron)
library(bdscale)
library(scales)
library(ggplot2)
library(dplyr)
df <- as.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)
ggplot(df, aes(x = day, y = client, color = scale, fill = scale)) + 
geom_tile() + 
# scale_x_date(date_breaks = "1 day") +
theme(axis.text.x = element_text(angle = 45)) +
scale_x_bd(business.dates = sort(df$day), max.major.breaks = 30, labels=scales::date_format('%d %b'))

也可以使用lubridatewday函数从周末删除数据,如下所示filter(!wday(day) %in% c(1,7))太阳/周六分别存储为 1 和 7。- 记入@AHart

最新更新