ggplot2 - 为图例

时间:2017-01-19 13:47:09

标签: r 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&amp; this类似的问题。我足够接近,但我希望“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,但我找不到一种明确的方法,只显示边线并在图例中按需添加它们。总而言之,我不需要显示乐队,而是显示乐队。 我确信有一个明显的方法,但现在我被困在这里......

1 个答案:

答案 0 :(得分: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