且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

合并单独的几何图层的图例

更新时间:2023-12-02 15:23:13

我们必须绘制两个不同的图例,但使它们彼此靠近(在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"))