In ggplot2, how can I add additional legend?

后端 未结 1 1350
粉色の甜心
粉色の甜心 2020-12-04 17:19

I\'m trying to build a map in ggplot2 using data from separate data frames.

library(maptools)

xx <- readShapePoly(system.file(\"shapes/sids.         


        
相关标签:
1条回答
  • 2020-12-04 17:48

    I'm not 100% sure this is what you want, but here's how I'd approach the problem as I understand it. If we map some unused geom with any data from xx.sub1.df, but make it invisible on the plot, we can still get a legend for that geom. Here I've used geom_point, but you could make it others.

    p <- ggplot(xx.sub2.df) + 
      aes(long, lat, fill = (SID79/BIR79)*1000, group = group) + 
      geom_polygon() + geom_path(color="grey80") +
      coord_equal() + 
      scale_fill_gradientn(colours = brewer.pal(7, "YlOrBr")) +
      geom_polygon(data = xx.sub1.df, fill = "grey50") + 
      geom_path(data = xx.sub1.df, color="grey80") +
      labs(fill = "Mapped value", title = "Title")
    
    #Now we add geom_point() setting shape as NA, but the colour as "grey50", so the 
    #legend will be displaying the right colour
    
    p2 <- p + geom_point(data = xx.sub1.df, aes(size="xx.sub1", shape = NA), colour = "grey50")
    

    enter image description here

    Now we just need to alter the size and shape of the point on the legend, and change the name of the legend (thanks to @DizisElferts who demonstrated this earlier).

    p2 + guides(size=guide_legend("Source", override.aes=list(shape=15, size = 10)))
    

    enter image description here

    Of course you can change the way the labels work or whatever to highlight what you want to show.

    If this isn't what you're after, let me know!

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