Rob*_*ger 2 r ggplot2 r-forestplot
作为 R 的新手(没有任何编码经验),我遇到以下问题。我正在尝试创建比值比的分组森林图(斑点图)。横轴应包含 OR。纵轴为变量。每个变量都包含 A 组和 B 组的 OR(包括下限和上限)。因此,垂直轴上显示的每个变量应该可见 2 条线。这个网站和这个网站应该给你一种分组的想法。
我从Mike Barnkob那里找到了一种相当不错的森林图格式,我一直在努力适应我的需求。
我一直在通过stackoverflow(例如这里)。使用这种方法,我必须分割数据帧,我想其他方法也是可能的。
请在下面找到代码,其中仅包含一组虚拟数据框。
df <- data.frame(Outcome=c("Outcome A", "Outcome B", "Outcome C", "Outcome D"),
OR=c(1.50, 2.60, 1.70, 1.30),
Lower=c(1.00, 0.98, 0.60, 1.20),
Upper=c(2.00, 3.01, 1.80, 2.20)
)
if (!require('ggplot2')) install.packages('ggplot2'); library('ggplot2')
Outcome_order <- c('Outcome C', 'Outcome A', 'Outcome B', 'Outcome D')
p <- ggplot(df, aes(x=factor (Outcome, level=Outcome_order), y=OR, ymin=Lower, ymax=Upper)) +
geom_linerange(size=5, colour="#a6d8f0") +
geom_hline(aes(x=0, yintercept=1), lty=2) +
geom_point(size=3, shape=21, fill="#008fd5", colour="white", stroke = 0.5) +
scale_x_discrete(name="(Post)operative outcomes") +
scale_y_continuous(name="Odds ratio", limits = c(0.5, 5)) +
coord_flip() +
theme_minimal()
p
p + annotate("text", x=4.1, y=2.25, label="*")
Run Code Online (Sandbox Code Playgroud)
有谁知道如何为每个变量添加第二组,最好在上面或旁边有一个图例?先感谢您!
诀窍是将它们组合成一个数据框,并在下面的示例中引入另一个变量“组”。当你绘制图时,你需要指定 postion=position_dodge() 以便它们并排绘制。看看下面是否是您想要的。我对颜色真的很不好,所以您可能需要为其他组指定颜色
library('ggplot2')
Outcome_order <- c('Outcome C', 'Outcome A', 'Outcome B', 'Outcome D')
#this is the first dataset you have
df1 <- data.frame(Outcome=c("Outcome A", "Outcome B", "Outcome C", "Outcome D"),
OR=c(1.50, 2.60, 1.70, 1.30),
Lower=c(1.00, 0.98, 0.60, 1.20),
Upper=c(2.00, 3.01, 1.80, 2.20))
# add a group column
df1$group <- "X"
# create a second dataset, similar format to first
df2 <- df1
# different group
df2$group <- "Y"
# and we adjust the values a bit, so it will look different in the plot
df2[,c("OR","Lower","Upper")] <- df2[,c("OR","Lower","Upper")] +0.5
# combine the two datasets
df = rbind(df1,df2)
# you can do the factoring here
df$Outcome = factor (df$Outcome, level=Outcome_order)
#define colours for dots and bars
dotCOLS = c("#a6d8f0","#f9b282")
barCOLS = c("#008fd5","#de6b35")
p <- ggplot(df, aes(x=Outcome, y=OR, ymin=Lower, ymax=Upper,col=group,fill=group)) +
#specify position here
geom_linerange(size=5,position=position_dodge(width = 0.5)) +
geom_hline(yintercept=1, lty=2) +
#specify position here too
geom_point(size=3, shape=21, colour="white", stroke = 0.5,position=position_dodge(width = 0.5)) +
scale_fill_manual(values=barCOLS)+
scale_color_manual(values=dotCOLS)+
scale_x_discrete(name="(Post)operative outcomes") +
scale_y_continuous(name="Odds ratio", limits = c(0.5, 5)) +
coord_flip() +
theme_minimal()
Run Code Online (Sandbox Code Playgroud)