将项目添加到现有图例

时间:2018-09-09 12:55:19

标签: r ggplot2 legend

我是ggplot2的新手,而且自几个小时以来一直在努力在情节中添加第二个图例。

我正在使用两个data.framesdf_1df_2)和两个geom_point呼叫它们。我设法为df_2创建了一个图例,但无法为df_1添加第二个图例。

下面是一个带有情节的代码示例:

########## Create sample data
set.seed(69)
df_1 = data.frame(lat = rnorm(20), 
                  lon = rnorm(20), 
                  cor = c(rep('positive', 12), rep('negative', 8)), 
                  sign = 0)

df_2 = data.frame(lat = rnorm(20), 
                  lon = rnorm(20), 
                  cor = c(rep('positive', 7), rep('negative', 13)), 
                  sign = c(rep(99, 5), rep(95, 6), rep(90,9)))

#### Plot data
library(ggplot2)
p = ggplot() +

    # geom_point for df_1
    geom_point(data=df_1, aes(x=lon, y=lat), 
               alpha=0.7, color = 'darkgrey', size = 3) +

    # geom_point for df_2
    geom_point(data=df_2, aes(x=lon, y=lat, size=sign, colour = cor), alpha = 0.5) +

    scale_color_manual(values=c("red", "blue"),
                       name='cor', 
                       labels = c('neg', 'pos'),
                       guide = guide_legend(override.aes = list(alpha = 1, size = 3))) +

    scale_size(range = c(1,3), 
               breaks = c(90, 95, 99),
               labels = c(0.1, 0.05, 0.01),
               name = 'sign',
               guide = guide_legend(override.aes = list(colour = 'black', 
                                                        alpha = 1)))

print(p)

enter image description here

如何为geom_point的{​​{1}}调用添加图例?

在带有“未签名”标签的cor(右图例)上添加第三个深灰色点就足够了。

1 个答案:

答案 0 :(得分:1)

我想直接的解决方案也是您要求的将第3个Darkgrey点添加到cor图例。为此,您必须:

  1. cor中的df_1值更改为相同。
  2. df_1 aes中指定颜色。
  3. 添加scale_color_manual中第三点的信息。

代码:

# Change values so we would have single color for them
df_1$cor <- "foo" 

library(ggplot2)
ggplot() +
    geom_point(aes(lon, lat, color = cor), df_1,
               alpha = 0.7, size = 3) +
    geom_point(aes(lon, lat, size = sign, colour = cor), df_2,
               alpha = 0.5) +
    scale_color_manual(values = c("darkgrey", "red", "blue"),
                       labels = c("not sign", "neg", "pos"),
                       guide = guide_legend(override.aes = list(alpha = 1, size = 3))) +
    scale_size(range = c(1, 3), 
               breaks = c(90, 95, 99),
               labels = c(0.1, 0.05, 0.01),
               guide = guide_legend(override.aes = list(colour = "black", alpha = 1)))

结果:

enter image description here