【问题标题】:Adding lines to grouped boxplots向分组箱线图添加线条
【发布时间】:2016-01-26 09:01:13
【问题描述】:

我有一个包含 3 个因素(Parent.organization、Hierarchy、变量)以及一个度量变量(值)的数据集,可以使用一些帮助。以下是一些相同风格的示例数据:

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 的了解正在提高,但我想说我仍然相当无能。也非常欢迎任何关于如何改进我的问题的建议。

【问题讨论】:

    标签: r ggplot2 data-visualization boxplot


    【解决方案1】:

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

    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.val 用于yyminymax 以获取行。 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")
    

    【讨论】:

    • 太棒了。一口气教会了我几件事。谢谢!