如何添加颜色等于分组变量的多个geom_hlines

use*_*490 1 r ggplot2

我创建了一个分组的boxplot,并添加了三个特定geom_hlines的情节.但是,我想将hline颜色设置为fill=factor(Training.Location),而不是尝试使用调色板手动匹配颜色.有没有办法做到这一点?

ggplot(aes(x=factor(CumDes),y=Mn_Handle), data=NH_C) +
    geom_boxplot( aes(fill=factor(Training.Location))) +
    geom_point( aes(color=factor(Training.Location)), 
    position=position_dodge(width=0.75) ) + 
    theme(axis.ticks = element_blank(), axis.text.x = element_blank()) + 
    coord_cartesian(ylim = c(0, 2000)) + 
    geom_hline(yintercept=432, linetype="dashed", lwd=1.2) + 
    geom_hline(yintercept=583, linetype="dashed", lwd=1.2) + 
    geom_hline(yintercept=439, linetype="dashed", lwd=1.2)
Run Code Online (Sandbox Code Playgroud)

aos*_*ith 6

对于新的数据集,这是最简单的事情.我不确定你是如何计算你用于水平线的值,但我经常想从原始数据集计算这些值并使用某种聚合函数/包.

以下是帮助页面中的修改示例geom_hline.

使数据集赋予geom_hline,包括水平线的值以及分组变量.

mean_wt = data.frame(cyl = c(4, 6, 8), wt = c(2.28, 3.11, 4.00))
Run Code Online (Sandbox Code Playgroud)

然后使用该分层变量的任何美学,使用该图层的新数据集进行绘图.

ggplot(mtcars, aes(x = factor(vs), wt) ) +
    geom_boxplot(aes(fill = factor(cyl))) +
    geom_point(aes(color = factor(cyl)), position = position_dodge(.75)) +
    geom_hline(data = mean_wt, aes(yintercept = wt, color = factor(cyl)) )
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述