Merge legends of separate geom layers

后端 未结 1 1318
执念已碎
执念已碎 2021-01-28 20:27

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 pr

相关标签:
1条回答
  • 2021-01-28 20:38

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

    0 讨论(0)
提交回复
热议问题