Merge legends of separate geom layers

感情迁移 提交于 2019-12-02 10:17:45

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"))

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!