r - 如何将甘特图功能添加到 ggplot
问题描述
我有一个人的血压读数图表。我也知道他们何时开始和停止各种抗高血压药物及其剂量。
如何在血压数据上方添加一个框,以显示任何特定药物的开始、停止和重新启动时间以及剂量?
我可能可以使用 ggtext 包,但看起来我想做的事情会很麻烦。是否有专门添加此类功能的软件包。
解决方案
这似乎是 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)
推荐阅读
- reactjs - 故事书和类型
- javascript - 如何使用 javascript 知道不透明度值?
- spring-boot - 使用 Postman 或 Insomnia 进行测试时,基于 Spring Boot 构建的 Rest API 总是重定向到 /login
- window - 使用 window.postMessage 发送函数
- ios - 函数中的完成处理程序
- encryption - 在我的 Mac mini 上哪里可以安全地存储哈希?
- github-api - 用于拉取请求的 Github 搜索 API:无法搜索 > 创建日期(即使相同的代码可用于搜索问题)
- google-cloud-platform - Google Cloud Platform 限制 Http 引荐来源网址无法按预期工作
- ruby-on-rails - 使用 Rails 和 Hotwire 提交表单时出错
- ionic-framework - 我在 Ionic 5 中创建了一个新页面,但我无法找到路径 URL