微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决使用 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

提前致谢。

解决方法

感谢 Axeman 的贡献,真的很有帮助!它适用于我的示例,但我在我的数据中尝试它时遇到了一些问题。但是,我对其进行了修改并且现在可以正常工作了,这是我受 Axeman 启发的解决方案:

breaksFUN <- function(x) {
  s <- round(c(seq(min(x) + 1.5,max(x) - 5.5,length.out = 4),max(x) - 1.5))
  s[s == 0] <- 1
  s[s > 31] <- 31
  s <- round(seq(range(s)[1],range(s)[2],length.out = 5))
  unique(s)
}

p + scale_x_continuous(breaks = breaksFUN)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。