使用 ggplot2 的初学者简单示例的森林图 [已编辑] [英] Forest plot for a beginner simple example using ggplot2 [edited]
问题描述
我想使用 ggplot2 创建森林图.
I would like to create a forest plot using ggplot2.
目标是创建一个包含 6 行 X1、X2、X3、X4、X5 和 X6 的森林图.这些标签应出现在左侧.垂直虚线应出现在 x=1 处.此外,在图的右侧,每行应显示均值和 95% CI.
The goal is to create a forest plot with 6 rows named X1, X2, X3, X4, X5, and X6. Labels for these should appear on the left hand side. A vertical dashed line should appear at x=1. Furthermore, on the right hand side of the plot the values of the mean followed by 95% CI should appear at each row.
我的数据具有以下均值、下 95% 区间和上 95% 区间:
My data has following mean, lower 95% interval, and upper 95% interval:
mean <- c(1.29,0.76,2.43,1.68,1.22,1.7)
lower <- c(0.84,0.50,1.58,1.1,0.8,1.11)
upper <- c(1.95,1.16,3.67,2.54,1.85,2.56)
其中 X1 对应于 1.29 (0.84,1.95) 等等.
Where X1 corresponds to 1.29 (0.84,1.95) and so forth.
我希望这不会问太多,希望这可以作为那些不熟悉在 R 中绘制森林图的人的指南,比如我.
I hope this is not too much to ask and hope this may serve as a guide for those who are unacquainted with drawing Forest plots in R such as myself.
推荐答案
如果您不熟悉 R,ggplot2 可能是一个不错的选择:基本语法适用于许多不同类型的绘图.
ggplot2 might be a good choice if you are new to R: the basic syntax is applicable to many different types of plots.
这是你的例子带有 geom_pointrange 的简单森林图.唯一的技巧是 ggplot 线图通常在 x 轴上放置标签,在 y 轴上放置定量数据;这可以通过coord_flip"函数来改变,然后在创建绘图之前颠倒标签的顺序:
Here's your e.g. of a simple forest plot with geom_pointrange. The only trick is that ggplot line plots normally place labels on the x axis and quantitative data on the y axis; this can be changed with the "coord_flip" function, and then by reversing the order of the labels before creating the plot:
label <- paste0("X", 1:6)
mean <- c(1.29,0.76,2.43,1.68,1.22,1.7)
lower <- c(0.84,0.50,1.58,1.1,0.8,1.11)
upper <- c(1.95,1.16,3.67,2.54,1.85,2.56)
df <- data.frame(label, mean, lower, upper)
# reverses the factor level ordering for labels after coord_flip()
df$label <- factor(df$label, levels=rev(df$label))
library(ggplot2)
fp <- ggplot(data=df, aes(x=label, y=mean, ymin=lower, ymax=upper)) +
geom_pointrange() +
geom_hline(yintercept=1, lty=2) + # add a dotted line at x=1 after flip
coord_flip() + # flip coordinates (puts labels on y axis)
xlab("Label") + ylab("Mean (95% CI)") +
theme_bw() # use a white background
print(fp)
这篇关于使用 ggplot2 的初学者简单示例的森林图 [已编辑]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!