Home > Enterprise >  How add legend in ggplot
How add legend in ggplot

Time:01-07

I've written this code:

ggplot()  
  geom_sf(aes(fill = dat$color_province))  
  theme_void()  
  
  geom_point(data = producer, 
             aes(x = producer$MX, y = producer$MY), size = 3, col = "green", shape = 17, alpha = 0.6)  
  
  geom_point(data = distribution, 
             aes(x = distribution$MX, y = distribution$MY), size = 4.5, col = "yellow", shape = 15)  
  
  geom_point(data = retailer, 
             aes(x = retailer$MX, y = retailer$MY), size = 3, col = "slateblue", shape = 16)  
  
  geom_point(data = Demand, 
             aes(x = Demand$MX, y = Demand$MY, size = Demand$De), col = "slateblue", shape = 17, alpha = 0.7)  
  
  scale_fill_manual(values = c("#ff3333", "#ffc266"),
                    name = "Situation")

and now I want to add a legend to identify all points in my plot. How can I do it?

CodePudding user response:

Here's an example on some data that everyone can run, since it uses built-in datasets that come with R. Here, I made color and size be dynamic aesthetics with the name of the series, and then mapped those series values to different aesthetic values using scale_*_manual. This generates an automatic legend. By giving each aesthetic the same name ("source" here), ggplot2 knows to combine them into one legend.

ggplot()  
  geom_point(data = mtcars,
             aes(x = wt, y = mpg, color = "mtcars", size = "mtcars"))  
  geom_point(data = attitude,
             aes(x = rating/20, y = complaints/3, color = "attitude", size = "attitude"))  
  scale_color_manual(values = c("mtcars" = "slateblue", "attitude" = "red"), name = "source")  
  scale_size_manual(values = c("mtcars" = 3, "attitude" = 4.5), name = "source")

enter image description here

  •  Tags:  
  • Related