2017-01-19 4 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

?なぜ破線は伝説の中になければならないのですか?おそらく、プロットのタイトルで指定するほうがよいでしょう。 "破線はX%信頼区間を表す"。 – bouncyball

答えて

2

guide_legendを使用して、CIに破線の線種を指定することができます。私は、これはあなたが望むものに近いと思う:

使用している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

関連する問題