合并单独的几何图层的图例 [英] Merge legends of separate geom layers

查看:97
本文介绍了合并单独的几何图层的图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从地图上的两个单独的图层绘制点数据,并希望在一个图例中显示两个图层的信息.

I am plotting point data from two separate layers on a map and would like to display the information of both layers in one legend.

下面是一些说明问题的代码:

Here's some code to illustrate the problem:

set.seed(42)  
lat1 <- rnorm(10, 54, 12)
long1 <- rnorm(10, 44, 12)
val1 <- rnorm(10, 10, 3)
lat2 <- rnorm(10, 54, 12)
long2 <- rnorm(10, 44, 12)
val2 <- rnorm(10, 10, 3)

df1 <- as.data.frame(cbind(long1, lat1, val1))
df2 <- as.data.frame(cbind(long2, lat2, val2))

library(ggplot2)
library(scales)

f <- ggplot() +
     geom_point(data=df1, aes(x=lat1, y=long1, size=val1, fill=val1), shape=21, alpha=0.6) +
     scale_size_continuous(range = c(2, 12), breaks=pretty_breaks(4)) +
     scale_fill_distiller(direction = -1, palette="RdYlBu", breaks=pretty_breaks(4)) +     
     guides(fill = guide_legend(), size = guide_legend()) +
     theme_minimal()
p <- f + geom_point(data=df2, aes(x=lat2, y=long2, color="val2"), shape=17, size=3) +
     scale_color_manual(values="black",name="")
p

我能管理的最好的办法是创建两个单独的图例,然后删除其中一个图例标题.理想情况下,实心圆圈和黑色菱形都应属于同一个图例,例如价值"和黑色菱形将显示为"NA".任何帮助深表感谢!

The best I can manage, is to create two separate legends and to then remove one of the legend titles. Ideally, both the filled circles and the black diamond would be part of the same legend called e.g. "Value" and the black diamond would read e.g. "NA". Any help is much appreciated!

推荐答案

我们必须绘制两个不同的图例,但使它们彼此靠近(在legend.spacing.y中使用负值需要ggplot2_3.0.0).这种方法带来了另一个问题-两个图例无法对齐,因此我们必须绘制另一组菱形(较大以匹配非菱形,但不可见alpha = 0)

We have to plot two different legends, but move them close to each other (using negative value in legend.spacing.y requires ggplot2_3.0.0). This approach creates another problem - two legends doesn't align, therefore we have to plot another set of diamonds (larger to match non-diamonds, but invisible alpha = 0)

ggplot() +
    geom_point(data = df1, 
               aes(lat1, long1, size = val1, fill = val1), 
               shape = 21, alpha = 0.6) +
    geom_point(data = df2, 
               aes(lat2, long2, color = "val2"), 
               shape = 17, size = 3) +
    geom_point(data = df2, 
               aes(lat2, long2, color = "val2"), 
               shape = 17, size = 11.5, alpha = 0) +
    scale_size_continuous(range = c(2, 12), breaks = pretty_breaks(4)) +
    scale_fill_distiller(direction = -1, palette = "RdYlBu", breaks = pretty_breaks(4)) +     
    scale_color_manual(values = "black", name = "Value\n") +
    labs(fill = NULL,
         size = NULL) +
    guides(fill = guide_legend(), 
           size = guide_legend(),
           color = guide_legend(order = 1)) +
   theme_minimal() +
   theme(legend.spacing.y = unit(-0.4, "cm"))

这篇关于合并单独的几何图层的图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆