Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change ggplot legend labels and names with two layers?

Tags:

r

ggplot2

ggmap

I am plotting the longitude and latitude coordinates of two different data frames in São Paulo map using ggmap and ggplot packages and want to label manually each legend layer:

update: I edited my code below to become fully reproducible (I was using the geocode function instead of get_map).

update: I would like to do this without combining the data frames.

require(ggmap)

sp <- get_map('sao paulo', zoom=11, color='bw')
restaurants <- data.frame(lon=c(-46.73147, -46.65389, -46.67610), 
                          lat=c(-23.57462, -23.56360, -23.53748))
suppliers <- data.frame(lon=c(-46.70819,-46.68155, -46.74376), 
                        lat=c(-23.53382, -23.53942, -23.56630))
ggmap(sp)+geom_point(data=restaurants, aes(x=lon, y=lat),color='blue',size=4)+geom_point(data=suppliers, aes(x=lon, y=lat), color='red', size=4)

enter image description here

I have looked to several questions and tried different ways without success. Does anyone know how can I insert legend and label the blue points as restaurants and the red points as suppliers?

like image 324
Davi Moreira Avatar asked Jun 22 '12 15:06

Davi Moreira


People also ask

How do I change the legend label in ggplot2?

You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))

How do I change labels in legend?

Change the legend name using select dataSelect your chart in Excel, and click Design > Select Data. Click on the legend name you want to change in the Select Data Source dialog box, and click Edit. Note: You can update Legend Entries and Axis Label names from this view, and multiple Edit options might be available.

How do you add data point labels to Ggplot?

To put labels directly in the ggplot2 plot we add data related to the label in the data frame. Then we use functions geom_text() or geom_label() to create label beside every data point. Both the functions work the same with the only difference being in appearance.


1 Answers

Now that your code is reproducible (thanks!):

dat <- rbind(restaurants,suppliers)
dat$grp <- rep(c('Restaurants','Suppliers'),each = 3)

ggmap(sp) + 
    geom_point(data=dat, aes(x=lon, y=lat,colour = grp),size = 4) + 
    scale_colour_manual(values = c('red','blue'))

enter image description here

like image 186
joran Avatar answered Nov 15 '22 05:11

joran