首页 > 解决方案 > R:使用 coord_trans 时 y 轴消失

问题描述

数据:

structure(list(Doy = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 
1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 
6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L), 
Greenup = c(108, NA, 107, NA, 108, 108, NA, 108, NA, 108, 
96, 96, 97, 115, 114, 115, 97, 96, 96, 114, 99, 98, 99, 99, 
99, 99, 99, 99, NA, 98, 93, 94, 94, 93, 94, 90, 92, 94, 90, 
90), Maturity = c(137, NA, 137, NA, 137, 137, NA, 137, NA, 
137, 147, 147, 145, 147, 147, 147, 146, 146, 146, 147, 123, 
124, 123, 124, 122, 124, 124, 123, NA, 124, 123, 122, 122, 
123, 122, 126, 124, 122, 125, 126), Senescence = c(285, NA, 
284, NA, 286, 285, NA, 286, NA, 285, 276, 275, 275, 275, 
275, 275, 274, 275, 275, 276, 269, 287, 255, 251, 277, 253, 
276, 281, NA, 252, 288, 286, 283, 277, 281, 274, 280, 285, 
288, 274), Dormancy = c(313, NA, 317, NA, 314, 316, NA, 315, 
NA, 317, 313, 313, 313, 313, 313, 314, 314, 314, 314, 313, 
329, 324, 324, 328, 326, 326, 326, 327, NA, 327, 323, 322, 
323, 324, 323, 315, 324, 323, 322, 315), Year = c(2016, 2016, 
2016, 2016, 2016, 2016, 2016, 2016, 2016, 2016, 2017, 2017, 
2017, 2017, 2017, 2017, 2017, 2017, 2017, 2017, 2018, 2018, 
2018, 2018, 2018, 2018, 2018, 2018, 2018, 2018, 2019, 2019, 
2019, 2019, 2019, 2019, 2019, 2019, 2019, 2019)), row.names = c(NA, 
-40L), class = "data.frame")

我正在通过以下方式创建一个情节:

library(tidyverse)
library(hrbrthemes)

df_uncert %>%
  pivot_longer(-c(Year,Doy)) %>%
  na.omit() %>%
  ggplot(., aes(y = Year, x = value, group = interaction(name,Year))) +
    geom_boxplot(position = "identity", size = 0.25, outlier.shape = NA, width = 0.5) +
    theme_ipsum() + ylab("") + xlab("Day of year") +
    annotate("text", y = 2015, x = c(95,135,280,320), 
       label = c("Greenup", "Maturity", "Senecence", "Dormancy"),
       size = 3) +
    scale_y_continuous(breaks = c(2016,2017,2018,2019), trans = "reverse") 

这里的问题是,我的注释层显然扩展了我不想要的背景网格。我的想法是使用coordwithclip = "off"来限制 yaxis(以及网格本身),但是当我这样做时+coord_trans(ylim=c(2016,2019)),yaxis 完全消失了,我不知道为什么。有什么建议么?

在此处输入图像描述

标签: rggplot2

解决方案


问题是您已经应用了transin scale_y_continuous。要解决此问题,您可以摆脱规模并利用coord_trans(y = "reverse", ylim=c(2016,2019), clip = "off"). 但是,设置限制也会删除超出限制范围的注释。为了解决这个问题,我plot.margin在顶部增加了 为注释腾出空间,用于将注释y=2016放置在限制内,但使用 将其向上移动vjust=-10

library(tidyverse)
library(hrbrthemes)

df_uncert %>%
  pivot_longer(-c(Year,Doy)) %>%
  na.omit() %>%
  ggplot(., aes(y = Year, x = value, group = interaction(name,Year))) +
  geom_boxplot(position = "identity", size = 0.25, outlier.shape = NA, width = 0.5) +
  theme_ipsum() + ylab("") + xlab("Day of year") +
  annotate("text", y = 2016, x = c(95,135,280,320), vjust = -10,
           label = c("Greenup", "Maturity", "Senecence", "Dormancy"),
           size = 3) +
  coord_trans(y = "reverse", ylim=c(2016,2019), clip = "off") +
  theme(plot.margin = margin(t = 80, r = 5.5, 5.5, 5.5))


推荐阅读