bob jones - 2 months ago 25x
R Question

# How to add labels to points conditionally in a city map using ggmap

I was trying to label points using name on the map conditionally for a city.

Data

``````name |s  Latitude |s Longitude |s Frequency

Pelham Bay Park | 40.865556 | -73.808333 | 32

Greenbelt        | 40.58846 | -74.139073  | 10

Van Cortlandt Park | 40.8978 | -73.8839 | 3

Flushing Meadowsâ€“Corona Park | 40.745833 | -73.844722 | 5

Central Park | 40.783333 | -73.966667 |22
``````

Code

``````library(ggmap)
town <- get_map(location = "New York", zoom = 10)

mapPoints <- ggmap(town) +
geom_point(aes(x = work_count\$Longitude, y = work_count\$Latitude, size = work_count\$Frequency), data = work_count, alpha = .5) +
geom_text(aes(label=ifelse(work_count\$Frequency>quart(work_count\$Frequency)[2],as.character(work_count\$name),'')),hjust=0,vjust=0)

quart <- function(x) {
x <- sort(x)
n <- length(x)
m <- (n+1)/2
if (floor(m) != m) {
l <- m-1/2; u <- m+1/2
} else {
l <- m-1; u <- m+1
}
c(Q1=median(x[1:l]), Q3=median(x[u:n]))
}
mapPoints
``````

I am getting the following error:
Error: Aesthetics must be either length 1 or the same as the data (5): label, x, y
Any help is appreciated

This seems to work.

``````work_count\$lab <- ifelse(work_count\$Frequency>quart(work_count\$Frequency)[2],
as.character(work_count\$name), '')

mapPoints <- ggmap(town,
base_layer = ggplot(work_count,
aes(x = Longitude, y = Latitude))) +
geom_point(aes(size = Frequency),
alpha = .5) +
geom_text(aes(label = labels),
vjust = 0,
hjust = 0)
mapPoints
``````