向分组箱线图添加线条

Adding lines to grouped boxplots

我有一个包含 3 个因素(Parent.organization、层次结构、变量)以及一个度量变量(值)的数据集,需要一些帮助。这是一些相同样式的示例数据:

sampleData <- data.frame(id = 1:100, 
Hierarchy = sample(c("Consultant", "Registrar", "Intern", "Resident"), 100, replace = TRUE),
                     Parent.organization = sample(c("Metropolitan", "Regional"), 100, replace = TRUE),
                     variable = sample(c("CXR", "AXR", "CTPA", "CTB"), 100, replace = TRUE),
                     value = rlnorm(20, log(10), log(2.5)))
summary(sampleData)

使用下面的代码我得到下面的图表

library(ggplot2)
library(scales)

p0 = ggplot(sampleData, aes(x = Hierarchy, y = value, fill = variable)) +
  geom_boxplot() 
plog = p0 + scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x),
                      labels = trans_format("log10", math_format(10^.x))) +
  theme_bw() +
 facet_grid(.~Parent.organization, scales = "free", space = "free")

我有一组要为每个扫描变量标记的值(这些值在层次结构的所有元素中都相同,并且代表真实值)。假设 AXR、CTB、CTPA、CXR 分别为 3、5、7、5。我想要这些叠加在上面,但我不确定如何进行。

我正在寻找类似的东西(我刚刚填写了前两个,但相同的模式将适用于所有领域):

我对 R 的了解正在提高,但我想说我仍然相当无能。也非常欢迎任何关于如何改进我的问题的建议。

首先,您必须为线创建新的数据框,其中您具有与原始数据框相同的分组和分面变量。所有组合都应重复所有数据。

true.df<-data.frame(Hierarchy =rep(rep(c("Consultant", "Registrar", "Intern", "Resident"),each=4),times=2),
                    Parent.organization = rep(c("Metropolitan", "Regional"),each=16),
                    variable = rep(c("AXR", "CTB", "CTPA", "CXR"),times=8),
                    true.val=rep(c(3,5,7,5),times=8))

然后你可以使用geom_crossbar()来添加这些行。对 yyminymax 使用 true.val 来获取行。 position=position_dodge() 将确保线条被闪避,show_guide=FALSE 将确保图例不受影响。

plog+geom_crossbar(data=true.df,aes(x = Hierarchy,y=true.val,ymin=true.val,
                                    ymax=true.val,fill=variable),
                   show_guide=FALSE,position=position_dodge(),color="red")