首页 文章

将行添加到分组的箱图

提问于
浏览
2

我有一个包含3个因子(Parent.organization,Hierarchy,variable)的数据集以及一个度量变量(value),可以使用一些帮助 . 以下是相同样式的一些示例数据:

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

enter image description here

我有一组我想为每个扫描变量标记的值(这些值在层次结构的所有元素中都是相同的,并表示真值) . 假设它们分别为AXR,CTB,CTPA,CXR分别为3,5,7,5 . 我希望这些覆盖在顶部,但我不确定如何继续 .

我正在追求类似的东西(我刚刚填写了前两个,但同样的模式将全面适用):

enter image description here

我对R的了解正在改善,但我会说我仍然相当无能 . 此外,对于如何改进我的问题的任何建议也非常欢迎 .

1 回答

  • 2

    首先,您必须为这些行创建新的数据框,其中您具有与原始数据框中相同的分组和构面变量 . 应对所有组合重复所有数据 .

    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() 添加行 . 使用 true.valyyminymax 获取行 . 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")
    

    enter image description here

相关问题