2017-01-19 42 views
0

鉴于一些数据,如:GGPLOT2 - 同色系但不同类型的增加线传说

my.data <- data.frame(time  = rep(1:3, 2), 
         means = 2:7, 
         lowerCI = 1:6, 
         upperCI = 3:8, 
         scenario = rep(c("A","Z"), each=3)) 
my.data 
#  time means lowerCI upperCI scenario 
# 1 1  2  1  3  A 
# 2 2  3  2  4  A 
# 3 3  4  3  5  A 
# 4 1  5  4  6  Z 
# 5 2  6  5  7  Z 
# 6 3  7  6  8  Z 

我需要像下面的一个,但一些标签的(信心)的阴谋虚线应该出现在传说 - 订单事宜,应该是像Z,A,CI-Z,CI-A(见下文)。 enter image description here 这是相应的代码:

ggplot(data = my.data) + 
# add the average lines 
geom_line(aes(x=time, y=means, color=scenario)) + 
# add "confidence" lines 
geom_line(aes(x=time, y=lowerCI, color=scenario), linetype="dotted") + 
geom_line(aes(x=time, y=upperCI, color=scenario), linetype="dotted") + 
# set color manually 
scale_color_manual(name = 'Scenario', 
        breaks = c("Z", "A"), 
        values = c("Z" = "red", 
           "A" = "blue")) 

下面是我的尝试后,我检查this & this SO类似的问题。我很接近,但我希望“CI”标签不要分开。

ggplot(data = my.data) + 
# add the average lines 
geom_line(aes(x=time, y=means, color=scenario)) + 
# add "confidence" lines 
geom_line(aes(x=time, y=lowerCI, color=scenario, linetype="CI")) + 
geom_line(aes(x=time, y=upperCI, color=scenario, linetype="CI")) + 
# set color manually 
scale_color_manual(name = 'Scenario', 
        breaks = c("Z", "A"), 
        values = c("Z" = "red", 
           "A" = "blue")) + 
# set line type manually 
scale_linetype_manual(name = 'Scenario', 
         breaks = c("Z", "A", "CI"), 
         values = c("Z" = "solid", 
           "A" = "solid", 
           "CI" = "dotted")) 

enter image description here

我也尝试过使用geom_ribbon的东西,但我无法找到一个明确的方法,使之只显示边缘线,并添加它们可以根据需要在传奇。总而言之,我不需要展示乐队,而是线条。 我确信有一个明显的方法,但现在我卡在这里...

+0

什么类型的CI您使用的是?为什么虚线必须在传说中?也许最好在剧情的标题中指定,例如“虚线表示X%置信区间”。 – bouncyball

回答

2

我们可以使用guide_legend来指定CI的虚线类型。我认为这是接近你想要什么:

ggplot(my.data, aes(x = time, y = means))+ 
    geom_line(aes(colour = scenario))+ 
    geom_line(aes(y = lowerCI, colour = paste(scenario, 'CI')), 
       linetype = 'dashed')+ 
    geom_line(aes(y = upperCI, colour = paste(scenario, 'CI')), 
       linetype = 'dashed')+ 
    scale_colour_manual(values = c('A' = 'red','Z' = 'blue', 
            'A CI' = 'red','Z CI' = 'blue'), 
         breaks = c('Z', 'Z CI', 'A', 'A CI'))+ 
    guides(colour = guide_legend(override.aes = list(linetype = c('solid', 'dashed'))))+ 
    ggtitle('Dashed lines represent X% CI') 

enter image description here