2017-09-18 95 views
1

我正在寻找一种方法,在图例中具有两个或更多个段以及Boxplot的中值。 我已经提出了下面的示例:将geom_segment和Boxplot的中值添加到图例

y = data.frame(runif(500)) 
library(ggplot2) 
ggplot(data = y)+ 
    aes(0, y)+ 
    geom_boxplot(outlier.shape = 1)+ 
    scale_y_continuous(name = "",limits = c(0,1))+ 
    scale_x_discrete(name = "")+ 
    geom_segment(aes(x=-0.362, y=0.6, xend=0.363,yend=0.6, linetype = "R 
    fans"), linetype = "dashed", colour = "black")+ 
    geom_segment(aes(x=-0.35, y=0.8, xend=0.35,yend=0.8, linetype = 
    "frustated R users"), col = "red")+ 
    theme_bw()+ 
    theme(legend.title = element_blank())+ 
    theme(legend.background = element_rect(fill="white", 
            size=0.1, linetype="solid", 
            colour ="black")) 

的geom_segment其中y = 0.6,应当与一个黑色虚线的图例。此刻,我选择了线型两次,这是没有道理的,但如果我删除第二个线型,图例中的颜色将变为红色,或者线型变为另一个不需要的线型。对于剧情以及传说来说,它应该是黑色的,并且是虚幻的。对于y = 0.8,效果很好,因为默认的线型是正确的。

另外,我想在图例中有第三行。第三行应该是中线,这是一条坚实的粗黑线。

感谢您提前提供任何帮助。

回答

1

解决方法是将线条分别作为data.frame,将单独的线条颜色设置为color = Group,并将这些颜色指定为scale_color_manual

library(ggplot2) 

# Generate data 
dBox <- data.frame(y = rnorm(10)) 
dLines <- data.frame(X =c(-0.362, -0.35), 
        Y = c(0.6, 0.8), 
        Xend = c(0.363, 0.35), 
        Yend=c(0.6, 0.8), 
        Group = c("typeA", "typeB"), 
        color = c("black", "red")) 


ggplot(dBox, aes(0, y)) + 
    geom_boxplot(outlier.shape = 1)+ 
    scale_y_continuous(name = "",limits = c(0,1))+ 
    scale_x_discrete(name = "") + 
    geom_segment(data = dLines, 
       aes(x = X, xend = Xend, 
        y = Y, yend = Yend, 
        color = Group)) + 
    scale_color_manual(values = dLines$color) + 
    theme_bw() + 
    theme(legend.title = element_blank()) + 
    theme(legend.background = element_rect(fill = "white", 
              size = 0.1, 
              linetype = "solid", 
              colour = "black")) 

enter image description here

+0

非常感谢您的帮助。我稍微增加了答案,以便我有两种不同的线型(请参见下面的答案)。但我仍然不知道如何将Boxplot的中线添加到图例中。一种方法是在中线之上添加第三行(geom_segment)。这是做到这一点的唯一方法吗? –

0

我增强PoGibas非常有帮助回答两个不同的线型,以及:

y = data.frame(runif(500)) 


dLines <- data.frame(X =c(-0.362, -0.35), 
       Y = c(0.6, 0.8), 
       Xend = c(0.363, 0.35), 
       Yend=c(0.6, 0.8), 
       Group = c("TypeA", "TypeB"), 
       color = c("black", "red"), 
       linetype = c("solid", "dashed")) 

ggplot(data = y)+ 
    aes(0, y)+ 
    geom_boxplot(outlier.shape = 1)+ 
    scale_y_continuous(name = "",limits = c(0,1))+ 
    scale_x_discrete(name = "")+ 
    geom_segment(data = dLines, 
      aes(x = X, xend = Xend, 
       y = Y, yend = Yend, 
       color = Group, 
       linetype = Group))+ 
    scale_color_manual(values = dLines$color) + 
    scale_linetype_manual(values = dLines$linetype) + 
    theme_bw()+ 
    theme(legend.title = element_blank())+ 
    theme(legend.background = element_rect(fill="white", 
            size=0.1, linetype="solid", 
            colour ="black")) 

enter image description here

+0

但传说中仍缺少Boxplot的中位数。 –