具有不同颜色文本标签的 R forestplot() 函数

R forestplot() function with different coloured text labels

提问人:user36196 提问时间:11/10/2023 最后编辑:user36196 更新时间:11/16/2023 访问量:84

问:

赏金将在 2 天后到期。这个问题的答案有资格获得 +100 声望赏金。User36196 希望引起人们对此问题的更多关注

森林图(使用 R forestplot() 函数)有没有办法在图的左侧有不同颜色的文本标签?

即我希望情节看起来像这样:enter image description here

带有不同颜色的左手标签。我可以绘制两个森林图并将它们粘贴在一起,但我更喜欢一种解决方案,该解决方案允许所有元素在单个图上正确排列(有 9 个标签需要在一组中是一种颜色,~20 个标签需要在另一组中是另一种颜色)

如果有,我将如何使用 forestplot() 函数和库来获取它?

编辑以添加可重现的代码片段:

编辑:提供最少的代码示例

library(forestplot)
library(tidyr)

cohort <- data.frame(Age = c(43, 39, 34, 55, 70, 59, 44, 83, 76, 44, 
                             75, 60, 62, 50, 44, 40, 41, 42, 37, 35, 55, 46), 
                     Group = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
                                         1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), levels = c("1","2"), class = "factor"))

age.lm <- lm(Age ~ Group, data = cohort)

age.data <- summary(age.lm)$coefficients[2,]

age.data <- rbind(c(0,0,0,1,"Group 1", "n=15"),
                  c(age.data[1], age.data[1]-age.data[2]*1.95, 
                  age.data[1]+age.data[2]*1.95, age.data[4], "Group 2", "n=7"))

colnames(age.data) <- c("mean","lower","upper","p-val","labeltext","numbers")

age.data <- data.frame(age.data)


age.data$mean <- as.numeric(age.data$mean)
age.data$lower <- as.numeric(age.data$lower)
age.data$upper <- as.numeric(age.data$upper)


age.plot <- forestplot(age.data,
           labeltext = c(labeltext,numbers),
           boxsize = 0.1,
           xlog = FALSE,
           clip=c(-20,20),
           xticks=c(-20,-10,0,10,20),
           txt_gp = fpTxtGp(ticks=gpar(cex=1)),
           align=c("l","c","l"))
           

这个片段生成了一个单色图,但我希望左侧的标签是不同的颜色。

编辑:最初看起来 fpColors() 可能会提供此功能,但它使用指定的颜色为行中的所有文本元素着色,而不仅仅是左侧的文本标签。

R-森林图

评论

0赞 Friede 11/10/2023
是的,有一些方法可以实现这一目标。
0赞 user36196 11/10/2023
如何使用 forestplot() 函数和相关库?
0赞 Yacine Hajji 11/15/2023
不要犹豫,分享一个可重现的例子,它将帮助人们回答并使其适合你使用它,一旦找到解决方案,你就会使用它
0赞 jared_mamrot 11/20/2023
我以前在 SO 上看过 @Thomas Lumley(作者);也许值得联系他询问潜在的解决方法?forestplot()

答:

2赞 Waldi 11/16/2023 #1

您可以使用参数通过 fpColors() 进行修改:coltext

forestplot(age.data,
           labeltext = c(labeltext,numbers),
           boxsize = 0.1,
           xlog = FALSE,
           clip = c(-20,20),
           xticks = c(-20,-10,0,10,20),
           txt_gp = fpTxtGp(ticks=gpar(cex=1)),
           align = c("l","c","l"),
           col = fpColors(text=c('red','blue'))
           )

enter image description here

评论

0赞 user36196 11/16/2023
我已经想出了如何做到这一点,但是如果我只想将标签“组 x”涂上颜色,而不是下一列怎么办?
0赞 Waldi 11/17/2023
我看到了你的最后一次编辑。 不幸的是,这似乎超出了包的参数化可能性,可能需要对函数进行重新编码。
1赞 user36196 11/22/2023
我已经在软件包页面上提出了此功能请求的 Github 问题,但我还没有得到回应,但我会将其作为该问题的部分答案