Multiple legends for a ggplot in R

2019-08-25 02:32发布

问题:

I have seen existing treads but i couldnt correct my code. I have to divide the legend "Segmentation" into two different legends. One legend should be showing (Run,Walk) and other legend should be telling the StayPoint(Yes, No). Issue is that, all the legend values gets mixed up and comes under the same legend heading. Can anyone tell me about it ? Thank you !

   ll_meanstt <- sapply(total_trajectory[1:2], mean)
   sq_map2tt <- get_map(location = ll_meanstt,  maptype = "roadmap", source 
   = "google", zoom = 21)
  sisquoctt <- 
  setNames(data.frame(total_trajectory$tt_lon,total_trajectory$tt_lat, 
  total_trajectory$tt_ids, total_trajectory$Trajectory_Segmentation, 
  total_trajectory$tt_speed, Staypoint), c("lon", "lat", "LocationID", 
  "Segmentation", "SpeedMetersPerSecond", "Staypoint"));



ggmap(sq_map2tt) + 
geom_point(data = sisquoctt, size = 12,  aes(fill = Staypoint, shape = 
Staypoint)) +

geom_point(data = sisquoctt, size = 8,  aes(fill = Segmentation, shape = 
Segmentation)) +

geom_line(data = sisquoctt, size = 3,  aes(color =SpeedMetersPerSecond)) +
geom_label_repel (data = sisquoctt, aes(label = paste("", 

as.character(LocationID), sep="")), 
                  angle = 60, hjust = 2, color = "indianred3",size = 4)

        lon      lat    LocationID Segmentation SpeedMetersPerSecond Staypoint
  1  5.010633 47.29399      W5232         Walk                  1.2        No
  2  5.010643 47.29400      W5769         Walk                  1.0       Yes
  3  5.010716 47.29398      W5234          Run                  1.5        No

回答1:

The problem is you have called geom_point() twice for data in the same x, y location and assigned the same aesthetics (fill and shape) to both Staypoint and Segmentation, so ggplot is putting them in the same legend. If you specify fill = for one variable, and shape = for the other, they should go into different legends. Also, not all points have fill aesthetics, you need to either select shapes that do(shapes 21 - 25 have fill), or use color =, an aesthetic that all ggplot2 points have.

Example using color instead of fill

ggmap(sq_map2tt) + 
geom_point(data = sisquoctt, size = 8,  aes(color = Staypoint, shape = Segmentation)) + 
geom_line(data = sisquoctt, size = 3,  aes(color = SpeedMetersPerSecond))

another approach if you want to use fill instead of color

ggmap(sq_map2tt) + 
    geom_point(data = sisquoctt, size = 8,  aes(fill = Staypoint, shape = Segmentation)) + 
    scale_shape_manual(values = c(21, 24) +
    geom_line(data = sisquoctt, size = 3,  aes(color = SpeedMetersPerSecond))


标签: r ggplot2