今天这篇推文,小编就带大家了解一下森林图(Forest Plot) 的绘制方法,主要内容如下:
森林图(Forest Plot) 常用于Meta分析结果展示使用。森林图(可以将观察到的效果、置信区间以及每个研究对象的权重等信息全部表示出来,是一种简单直观地展示单一研究和汇总研究的可视化图表。下面,小编再附上森林图各个绘图元素间关系的解释图:
Key Elements of the Forest plot
注:这里小编简单介绍一下,感兴趣的同学可以自行查阅资料哈。
下面小编就介绍下如何使用R和Python绘制森林图(Forest Plot),可视化结果可能会有所不同。
使用R绘制森林图(Forest Plot)的方法比较多,这里重点介绍R-forestplot包和R-ggforestplot包绘制。
「注意」:安装R-ggforestplot包之前,确保broom包已安装,否则可能会安装出错。
这一部分我们直接使用提供的数据进行绘制,重点在于展示forestplot包中一些绘图参数的设置。
「样例一」:
library(tidyverse)
library(forestplot)
library(meta)
# 构建数据集
cochrane_from_rmeta <-
structure(list(
mean = c(NA, NA, 0.578, 0.165, 0.246, 0.700, 0.348, 0.139, 1.017, NA, 0.531),
lower = c(NA, NA, 0.372, 0.018, 0.072, 0.333, 0.083, 0.016, 0.365, NA, 0.386),
upper = c(NA, NA, 0.898, 1.517, 0.833, 1.474, 1.455, 1.209, 2.831, NA, 0.731)),
.Names = c("mean", "lower", "upper"),
row.names = c(NA, -11L),
class = "data.frame")
# 可视化绘制
forestplot(tabletext,
graph.pos = 4,
# 修改label,ticks 字体和大小
txt_gp = fpTxtGp(label = gpar(fontfamily = "Roboto Condensed"),
ticks = gpar(fontfamily = "Roboto Condensed", cex = .8)),
hrzl_lines = gpar(col = "#444444"),
cochrane_from_rmeta,new_page = TRUE,
is.summary = c(TRUE,TRUE,rep(FALSE,8),TRUE),
clip = c(0.1,2.5),
xlog = TRUE,
col = fpColors(box = "#BC3C28",
line = "black",
summary = "#BC3C28"),
vertices = TRUE,
title = "The Example Of forestplot::forestplot()")
The Example Of forestplot::forestplot()
注意:这里设置了graph.pos=4 参数用于改变图表元素位置。
「样例二」:针对多个置信区间时
# 构建数据
data(HRQoL)
clrs <- fpColors(box = "royalblue",line = "darkblue", summary = "royalblue")
tabletext <-
list(c(NA, rownames(HRQoL$Sweden)),
append(list(expression(beta)), sprintf("%.2f", HRQoL$Sweden[,"coef"])))
tabletext <- cbind(rownames(HRQoL$Sweden),
sprintf("%.2f", HRQoL$Sweden[,"coef"]))
tabletext02 <- tabletext[,1]
#可视化绘制
forestplot(tabletext02,
legend = c("Sweden", "Denmark"),
fn.ci_norm = c(fpDrawNormalCI, fpDrawCircleCI),
txt_gp = fpTxtGp(label = gpar(fontfamily = "Roboto Condensed"),
ticks = gpar(fontfamily = "Roboto Condensed", cex = .8),
xlab = gpar(fontfamily = "Roboto Condensed", cex = 1)),
boxsize = .25, # 设置box 大小
line.margin = .1, # 设置该参数,避免拥挤
mean = cbind(HRQoL$Sweden[, "coef"], HRQoL$Denmark[, "coef"]),
lower = cbind(HRQoL$Sweden[, "lower"], HRQoL$Denmark[, "lower"]),
upper = cbind(HRQoL$Sweden[, "upper"], HRQoL$Denmark[, "upper"]),
clip = c(-.125, 0.075),
xticks = c(-.1, -0.05, 0, .05),
lty.ci = c(1, 2),
col = fpColors(box = c("#BC3C28", "#0972B5")),
xlab = "EQ-5D index",vertices = TRUE,
title = "The Example02 Of forestplot::forestplot()")
The Example02 Of forestplot::forestplot()
以上就简单介绍了forestplot包绘制森林图(Forest Plot),更多详细参数设置和例子,小伙伴们参考forestplot介绍[1]
ggforestplot包符合ggplot2绘图语法,熟悉ggplot2的小伙伴可能更加适应一下,接下来,小编举几个例子具体介绍下~
「样例一:」 forestplot()函数绘制
library(ggforestplot)
library(tidyverse)
df_linear <-
ggforestplot::df_linear_associations %>%
dplyr::arrange(name) %>%
dplyr::filter(dplyr::row_number() <= 30)
# 可视化绘制
ggforestplot::forestplot(
df = df_linear,
estimate = beta,
logodds = FALSE,
colour = trait,
title = "Associations to metabolic traits",
xlab = "1-SD increment in cardiometabolic trait
per 1-SD increment in biomarker concentration"
)
The Example01 Of ggforestplot::forestplot()
「样例二」:geom_effect()绘制
这个方法和平时使用ggplot2绘制类似,也可以实现更加方便的定制化操作,如下:
df <-df_linear_associations %>%
# 数据处理
dplyr::arrange(name) %>%
dplyr::mutate(
xmin = beta - qnorm(1 - (1 - 0.95) / 2) * se,
xmax = beta + qnorm(1 - (1 - 0.95) / 2) * se
) %>%
dplyr::filter(dplyr::row_number() <= 30) %>%
dplyr::mutate(filled = pvalue < 0.001)
# 可视化绘制
ggplot(data = df, aes(x = beta, y = name)) +
geom_effect(
ggplot2::aes(
xmin = xmin,
xmax = xmax,
colour = trait,
shape = trait,
filled = filled
),
size=1.2,
position = ggstance::position_dodgev(height = 0.5)
) +
scale_colour_nejm() +
labs(
title = "Example of <span style='color:#D20F26'>ggforestplot::geom_effect function</span>",
subtitle = "processed charts with <span style='color:#1A73E8'>geom_effect()</span>",
caption = "Visualization by <span style='color:#0057FF'>DataCharm</span>") +
theme_forest() +
# Add striped background
geom_stripes() +
# Add vertical line at null point
geom_vline(
xintercept = 0,
linetype = "solid",
size = 0.4,
colour = "black"
) +
theme(text = element_text(family = "Roboto Condensed"),
plot.title = element_markdown(hjust = 0.5,vjust = .5,color = "black",face = 'bold',
size = 20, margin = margin(t = 10, b = 12)),
plot.subtitle = element_markdown(hjust = 0,vjust = .5,size=15),
plot.caption = element_markdown(face = 'bold',size = 12))
The Example01 Of ggforestplot::geom_effect()
以上,小编就简单介绍了使用R-ggforestplot()绘制森林图(Forest Plot)的绘制方法,更多绘图函数和图形参数,小伙伴们可参考R-ggforestplot包介绍[2]。
最后,小编再介绍使用survminer::ggforest()函数绘制制森林图(Forest Plot),详细如下:
「样例一」:
library(survminer)
library(survival)
model <- coxph( Surv(time, status) ~ sex + rx + adhere,
data = colon )
plot01 <- ggforest(model) +
labs(
title = "Example of <span style='color:#D20F26'>survival::ggforest function</span>",
subtitle = "processed charts with <span style='color:#1A73E8'>ggforest()</span>",
caption = "Visualization by <span style='color:#0057FF'>DataCharm</span>") +
theme(text = element_text(family = "Roboto Condensed"),
plot.title = element_markdown(hjust = 0.5,vjust = .5,color = "black",face = 'bold',
size = 20, margin = margin(t = 10, b = 12)),
plot.subtitle = element_markdown(hjust = 0.5,vjust = .5,size=15),
plot.caption = element_markdown(hjust = 1,face = 'bold',size = 11,margin = margin(b = 5,r = 5)))
The Example01 Of survminer::ggforest()
「样例二」:
colon <- within(colon, {
sex <- factor(sex, labels = c("female", "male"))
differ <- factor(differ, labels = c("well", "moderate", "poor"))
extent <- factor(extent, labels = c("submuc.", "muscle", "serosa", "contig."))
})
bigmodel <-
coxph(Surv(time, status) ~ sex + rx + adhere + differ + extent + node4,
data = colon )
plot02 <- ggforest(bigmodel) +
labs(
title = "Example of <span style='color:#D20F26'>survival::ggforest function</span>",
subtitle = "processed charts with <span style='color:#1A73E8'>ggforest()</span>",
caption = "Visualization by <span style='color:#0057FF'>DataCharm</span>") +
theme(text = element_text(family = "Roboto Condensed"),
plot.title = element_markdown(hjust = 0.5,vjust = .5,color = "black",face = 'bold',
size = 20, margin = margin(t = 10, b = 12)),
plot.subtitle = element_markdown(hjust = 0.5,vjust = .5,size=15),
plot.caption = element_markdown(hjust = 1,face = 'bold',size = 11,margin = margin(b = 5,r = 5)))
The Example02 Of survminer::ggforest()
更多详细例子可参考R-survminer[3]
Python在绘制森林图(Forest Plot)时可能没R这么方便,但小编也是找到一个可快速绘制的库-zepid。感兴趣的小伙伴可自行搜索,这里小编就接单介绍一下其EffectMeasurePlot()绘图函数,如下:
import matplotlib.image as mpimg
import numpy as np
import matplotlib.pyplot as plt
import zepid
from zepid.graphics import EffectMeasurePlot
plt.rcParams['font.family'] = ['Times New Roman']
labs = ["ACA(Isq=41.37% Tausq=0.146 pvalue=0.039 )",
"ICA0(Isq=25.75% Tausq=0.092 pvalue=0.16 )",
"ICA1(Isq=60.34% Tausq=0.121 pvalue=0.00 )",
"ICAb(Isq=25.94% Tausq=0.083 pvalue=0.16 )",
"ICAw(Isq=74.22% Tausq=0.465 pvalue=0.00 )"]
measure = [2.09,2.24,1.79,2.71,1.97]
lower = [1.49,1.63,1.33,2.00,1.25]
upper = [2.92,3.07,2.42,3.66,3.11]
p = EffectMeasurePlot(label=labs, effect_measure=measure, lcl=lower, ucl=upper)
p.labels(effectmeasure='RR')
p.colors(pointshape="D")
ax=p.plot(figsize=(8,4), t_adjuster=0.09, max_value=4, min_value=0.35)
plt.title("Random Effect Model(Risk Ratio)",loc="right",x=1, y=1.045)
plt.suptitle("Missing Data Imputation Method",x=-0.1,y=0.98)
ax.set_xlabel("Favours Control Favours Haloperidol ", fontsize=10)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(True)
ax.spines['left'].set_visible(False)
plt.savefig(r"forest_plot02_python.png",width=8,height=6,
dpi=900,bbox_inches='tight',facecolor='white')
Example Of EffectMeasurePlot() in Python
此外,zepid库还提供了其他绘图函数,感兴趣的小伙伴可阅读Python-zepid[4]
今天这篇推文,小编汇总了如何使用R和Python绘制森林图(Forest Plot)。使用的方法也较为简单,希望可以给小伙伴们带来绘图便利,当然,更多绘图函数和参数,还需自行探索哈~~
再小的技能,也应该被认真对待。
[1]
forestplot包介绍:https://cran.r-project.org/web/packages/forestplot/vignettes/forestplot.html。
[2]
ggforestplot包官网:https://nightingalehealth.github.io/ggforestplot/articles/ggforestplot.html。
[3]
survminer官网:https://rpkgs.datanovia.com/survminer/index.html。
[4]
zepid官方文档:https://zepid.readthedocs.io/en/latest/index.html。