One ggplot with multiple data sets

Viewed 137

I try to place points on a map so I am using ggmap. For the points, I have two separate data sets and the sample is below.

dta1 = data.frame(storename = c(letters[1:5]),
                      storesize = c("small","small","medium","large","large"),
                      lon = c(10,11.2,15,19,22),
                      lat = c(5,5.8,5.6,6.1,3.4))
    dta2 = data.frame(population = sample(100,100,replace = T),
                      lon = runif(100,10,22),
                      lat = runif(100,3.5,6))


Here is the sample code for the plot. In my real data set, I have ggmap(map) instead of ggplot(). Why below code does not work?

ggplot() + geom_point(data=dta1,
                      aes(x=lon, y=lat,size = storesize), shape = 23,fill="blue") + 
  scale_size_manual(values = c(1,2,3)) +
  geom_point(data=dta2,
             aes(x=lon, y=lat,size = population), shape = 21,fill="orange")

If I run those separately like this, it works

ggplot() + geom_point(data=dta1,
                      aes(x=lon, y=lat,size = storesize), shape = 23,fill="blue") + 
  scale_size_manual(values = c(1,2,3))

ggplot() +  geom_point(data=dta2,
             aes(x=lon, y=lat,size = population), shape = 21,fill="orange")

I would like to have one plot with two separate legends as each separated plot shows.

In addition, if I need to point one more particular place with a different shape (let's say shape = 11), how should I do it?

1 Answers

A solution is described here and here.
Install ggnewscale and then add a new scale using new_scale:

library(ggplot2)
library(ggnewscale)

dta1 = data.frame(storename = c(letters[1:5]),
                      storesize = c("small","small","medium","large","large"),
                      lon = c(10,11.2,15,19,22),
                      lat = c(5,5.8,5.6,6.1,3.4))
dta2 = data.frame(population = sample(100,100,replace = T),
                      lon = runif(100,10,22),
                      lat = runif(100,3.5,6))

ggplot() + 
geom_point(data=dta1,  aes(x=lon, y=lat,size=storesize), shape=23, fill="blue") + 
scale_size_manual(values = c(1,2,3)) +
new_scale("size") +
geom_point(data=dta2, aes(x=lon, y=lat, size=population), shape=21, fill="orange")

enter image description here

Related