首页 > 解决方案 > 如何将甘特图功能添加到 ggplot

问题描述

我有一个人的血压读数图表。我也知道他们何时开始和停止各种抗高血压药物及其剂量。

如何在血压数据上方添加一个框,以显示任何特定药物的开始、停止和重新启动时间以及剂量?

这是我正在尝试做的一个虚构的绘图。 我想要的图表

我可能可以使用 ggtext 包,但看起来我想做的事情会很麻烦。是否有专门添加此类功能的软件包。

标签: rggplot2

解决方案


这似乎是 Paul Murrell 在 github 上的 {gggrid} 包的用例。该软件包允许您以 ggplot2/grid 混合方式灵活地绘制任何内容。

根据您的情节,我假设您的数据大致呈以下形状:

library(ggplot2)
library(gggrid) # remotes::install_github("pmur002/gggrid")
#> Loading required package: grid

df <- data.frame(
  x = seq(Sys.Date(), Sys.Date() + 60, by = 1),
  y = cumsum(rnorm(61))
)

以及治疗的一些注释。

annotation <- data.frame(
  label = c("Cardelevovol", "Lisinopril 50 mg", "Lisonopril 100 mg"),
  xmin = Sys.Date() + c(0, 0, 40),
  xmax = Sys.Date() + c(40, 20, 60),
  y = c(1, 0, 0),
  fill = c("red", "white", "white")
)

然后我们可以定义一个函数,该函数将在绘图的上边缘绘制带标签的矩形。

annotate_fun <- function(data, coords) {
  textheight <- unit(1, "lines")
  
  rectangles <- rectGrob(
    x = (coords$xmin + coords$xmax) / 2,
    width = coords$xmax - coords$xmin,
    y = (data$y + 0.5) * textheight + unit(1, "npc"), 
    height = textheight,
    gp = gpar(fill = coords$fill)
  )
  
  text <- textGrob(
    label = data$label,
    x = (coords$xmin + coords$xmax) / 2,
    y = (data$y + 0.5) * textheight + unit(1, "npc")
  )
  
  gList(rectangles, text)
}

然后我们可以将其提供给gggrid::grid_panel()函数。

ggplot(df, aes(x, y)) +
  geom_point() +
  geom_smooth(method = "loess", formula = y ~ x) +
  grid_panel(
    annotate_fun, data = annotation,
    aes(xmin = xmin, xmax = xmax, 
        label = label, fill = I(fill), x = NULL)
  ) +
  # Turn off clipping and add some extra margin in top
  coord_cartesian(clip = "off") +
  theme(plot.margin = margin(35, 5.5, 5.5, 5.5))
#> Warning: Ignoring unknown aesthetics: xmin, xmax, label, fill

reprex 包于 2021-10-07 创建(v2.0.1)


推荐阅读