繁体   English   中英

从热图中的 x 轴排除周末

[英]exclude weekends from x axis in heatmap

我已经使用 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)) Sun/Sat 分别存储为 1 和 7。 - 归功于@AHart

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM