简体   繁体   English

从热图中的 x 轴排除周末

[英]exclude weekends from x axis in heatmap

I have coded a heatmap using ggplot tiles and it has sequencial days on the x axis .我已经使用 ggplot 块编码了一个热图,它在 x 轴上有连续的天数。 The problem I am trying to solve is to remove weekends from the heatmap and show only weekdays.我试图解决的问题是从热图中删除周末并仅显示工作日。 I have found that one solution would be to transform the dates into factors but if I do that how can I format the labels in scale_x_discrete to be in %d%m date format ?我发现一种解决方案是将日期转换为因子,但如果我这样做,我如何将 scale_x_discrete 中的标签格式化为 %d%m 日期格式? Is there a way to keep the dates as date format instead of turning it into factors ?有没有办法将日期保留为日期格式而不是将其转换为因子? Below is an example:下面是一个例子:

    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")

Thanks in advance提前致谢

You can exclude data from weekends using the is.weekend function from chron您可以使用排除周末数据is.weekend从功能chron

The weekend dates themselves can be excluded from an x-axis using the bdscale package可以使用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'))

Removing data from weekends can also be done using lubridate and the wday function as filter(!wday(day) %in% c(1,7)) Sun/Sat are stored as 1 and 7 respectively.从周末删除数据也可以使用lubridatewday函数作为filter(!wday(day) %in% c(1,7)) Sun/Sat 分别存储为 1 和 7。 - Credit to @AHart - 归功于@AHart

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

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