Home > Blockchain >  A custom legend unrelated to data in ggplot
A custom legend unrelated to data in ggplot

Time:06-10

Is it possible to create a custom legend in ggplot that is unrelated to data (as if you added it using the Photoshop)?

library(ggplot2)
library(ggmap)

# ================ Mapping =================== 
bas = get_stamenmap(c(-6.3, 53.25, -6, 53.40), zoom=7, maptype="terrain-background")
(mp <- ggmap(bas))


locs <-  data.frame( lon_dec = c(-6.04015), 
                     lat_dec = c( 53.3345))

(big_map <- mp  
    geom_point(data=locs, aes(x=lon_dec, y=lat_dec))   
    annotate(geom = "text", x = -6.04015, y = 53.3395, label = "1,2,3"))

the code gives the below plot (except I added the legend manually using Photoshop):

enter image description here

I want a legend next to the map saying:

1- A
2- B
3- C

Any help would be appreciated.

CodePudding user response:

To get a custom legend like this, it is probably easiest to add it as a custom annotation. You will need to switch to CoordCartesian with clipping off to do this.

(big_map <- mp  
    geom_point(data=locs, aes(x=lon_dec, y=lat_dec))   
    annotate(geom = "text", x = -6.04015, y = 53.3395, label = "1,2,3") 
    theme(plot.margin = margin(20, 100, 20, 20)))

big_map$coordinates <- coord_cartesian(clip = "off")

big_map   annotation_custom(
  grid::textGrob(x = 1.1, y = 0.5, label = "1 - A\n2 - B\n3 - C"))

enter image description here

  • Related