将标签添加到注释矩形ggplot

Add label to annotation rect ggplot

我正在制作情节行为变化加班。我想包括阴影区域以强调某些阶段。目前我正在使用 annotate("rect" x=POSIXct("").. 添加阴影区域,然后添加 annotate("label")...

有没有办法将标签直接添加到阴影区域,标签文本的大小和换行会发生变化以适应阴影区域?或者,是否有更有效的方法尝试将标签定位在日期范围阴影区域中?

    myDF <- labeled_rectxlsx

> str(myDF)
tibble [37 × 3] (S3: tbl_df/tbl/data.frame)
$ schDate   : POSIXct[1:37], format: "2020-10-22" "2020-10-23" "2020-11-09"
"2020-11-12" ...
$ rating    : num [1:37] NA NA NA NA NA NA NA NA NA NA ...
$ rect_label: chr [1:37] NA NA NA NA ...

schDate rating   rect_label
...
  11 2020-12-14     NA         <NA>
  12 2020-12-15     NA         <NA>
  13 2020-12-16     NA         <NA>
  14 2020-12-17     NA         <NA>
  15 2020-12-18     NA Winter Break
16 2021-01-03     NA         <NA>
  17 2021-01-04      6         <NA>
  18 2021-01-05      8         <NA>
  19 2021-01-06      5         <NA>
  20 2021-01-07      8         <NA>
  21 2021-01-08      7         <NA>
  22 2021-01-11      6         <NA>
  
maxY <- max(labeled_rectxlsx$rating, na.rm=TRUE)
insideY= (maxY*.98)



p <- myDF %>%
  ggplot(aes(x= schDate, y=rating))+
  geom_point()+
  geom_line()+
  theme_classic()+
  theme(
    plot.title = element_text(size=20, face="bold"),
    axis.title.x = element_blank(),
    axis.title.y = element_text(size=14, face="bold"),
    axis.text.x = element_text(size=12),
    axis.text.y = element_text(size=12))+
    annotate("rect",
           xmin = as.POSIXct("2020-12-19"), xmax = as.POSIXct("2021-01-03"), 
           ymin = -Inf, ymax = Inf, fill = "gray", alpha =.5)+
    annotate("label", x=as.POSIXct("2020-12-27"), 
           y= insideY , label="Winter Break", fill="black", color="white",fontface="bold",
           size=4, vjust="inward")
  
p

要稍微扩展评论,您可以使用带有虚拟 data.frame 的 ggfittext 包来保存值,并结合 inherit.aes = FALSE.

示例如下:

library(ggfittext)
#> Warning: package 'ggfittext' was built under R version 4.0.3
library(ggplot2)

set.seed(0)

myDF <- data.frame(
  schDate = seq(Sys.Date() - 100, Sys.Date(), by = "1 day"),
  rating = cumsum(rnorm(101))
)

ggplot(myDF, aes(schDate, rating)) +
  geom_point() +
  geom_line() +
  annotate("rect",
           xmin = as.Date("2020-12-19"), xmax = as.Date("2021-01-03"), 
           ymin = -Inf, ymax = Inf, fill = "gray", alpha =.5) +
  geom_fit_text(
    data = data.frame(xmin = as.Date("2020-12-19"), xmax = as.Date("2021-01-03"), 
                      label = "Winter Break"),
    aes(xmin = xmin, xmax = xmax, ymin = 4, ymax = 5, label = label),
    inherit.aes = FALSE
  )

reprex package (v1.0.0)

于 2021-02-09 创建