R forestplot() function with different coloured text labels

187 views Asked by At

Is there a way in a forestplot (using the R forestplot() function) to have text labels in different colours on the left hand side of the plot?

i.e. I'd like the plot to look like: enter image description here

with different coloured left hand labels. I could plot two forest plots and paste them together, but I'd prefer a solution which would allow all elements to line up correctly on a single plot (there are 9 labels that need to be one colour in one group and ~20 that need to be another in the other group)

If there is, how would I proceed with the forestplot() function and the library to obtain this?

Edit to add a reproducible code snippet:

EDIT: to provide a minimum code example

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"))
           

This snippet generates a monochrome plot, but I want the labels on the left hand side to be different colours.

EDIT: It initially looks like fpColors() might provide this functionality, but it colours all the text elements in the row with the specified colour, and not just the text label on the left hand side.

1

There are 1 answers

3
Waldi On BEST ANSWER

You could use the col argument to modify text with fpColors():

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