使用 facet_grid 在 ggplot 中自动设置数据代表中断

问题描述

以下是取自 the R Graph Gallery 的可复制示例:

library(ggplot2)
library(dplyr) 
library(viridis) 
library(Interpol.T) 
library(lubridate) 
library(ggExtra) 
library(tidyr) 


data <- data(Trentino_hourly_T,package = "Interpol.T")

names(h_d_t)[1:5]<- c("stationid","date","hour","temp","flag")
df <- as_tibble(h_d_t) %>%
  filter(stationid =="T0001")

df$date<-ymd(df$date)

df <- df %>% mutate(date = ymd(date),year = year(date),month = month(date,label=TRUE),day = day(date))

rm(list=c("h_d_t","mo_bias","Tn","Tx","Th_int_list","calibration_l","calibration_shape","Tm_list"))

df <- df %>%
  filter(between(date,as.Date("2004-02-13"),as.Date("2004-04-29")) | between(date,as.Date("2005-02-13"),as.Date("2005-04-29")))

df <-df %>% select(stationid,day,hour,month,year,temp)%>%
  fill(temp)

statno <-unique(df$stationid)


######## Plotting starts here#####################
p <-ggplot(df,aes(day,fill=temp))+
  geom_tile(color= "white",size=0.1) + 
  scale_fill_viridis(name="Hrly Temps C",option ="C") + 
  facet_grid(year~month,scales = "free") +
  scale_y_continuous(trans = "reverse",breaks = unique(df$hour)) + 
  theme_minimal(base_size = 8) + 
  labs(title= paste("Hourly Temps - Station",statno),x="Day",y="Hour Commencing") + 
  theme(legend.position = "bottom",plot.title=element_text(size = 14,hjust = 0),axis.text.y=element_text(size=6),strip.background = element_rect(colour="white"),axis.ticks=element_blank(),axis.text=element_text(size=7),legend.text=element_text(size=6))+
  removeGrid()

Default x axes breaks

让我困扰的是 x 轴中断没有明确显示每个月的第一天和最后一天,更糟糕的是它们显示了 2 月 30 日、3 月 0 日和 4 月 0 日。

我的目标是使用一个函数来自动显式地显示每个绘制月份的真实第一天和最后一天(在示例中为 2 月 13 日 - 2 月 29 日、3 月 1 日 - 3 月 31 日和 4 月 1 日 - 4 月 29 日)和 4 到每月 6 次休息。

由于此图将显示在一个闪亮的应用程序中,用户可以在其中更改绘制的时间段,因此该解决方案确实需要自动化。

以下是我尝试过的一些方法:

library(scales)
p + scale_x_continuous(breaks =breaks_pretty())

breaks_pretty() axes breaks

但变化不大。

我尝试编写自己的函数,但发生了一些可怕的事情:

breaksFUN <- function(x){
  round(seq(min(x),max(x),length.out = 5),0)
}

p + scale_x_continuous(breaks =breaksFUN)

breaksFUN axes breaks

提前致谢。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)