Getting a map with points, using ggmap and ggplot2
Your longitude and latitude values in geom_point()
are in wrong order. lon
should be as x
values and lat
as y
values.
p + geom_point(data=d, aes(x=lon, y=lat),size=5)
Plotting lines over maps in R with ggplot2/ggmap
Since there is no reproducible data, I created a random data. Please provide your data from next time. This is a necessary thing for all SO users when they ask some help.
What you need is to create a data frame for geom_segment. You do not have to loop through the data at all. Each row of of mydf
is a line. You specify two points for longitude and latitude, respectively using x
, y
, xend
and yend
.
library(ggmap)
library(ggplot2)
# Create a data frame for segments.
mydf <- data.frame(id = 1:3,
lat_1 = c(37.78, 37.75, 37.73),
lon_1 = c(-122.41, -122.40, -122.405),
lat_2 = c(37.77, 37.75, 37.72),
lon_2 = c(-122.43, -122.42, -122.415))
# Create randam data points.
set.seed(111)
mydf2 <- data.frame(lon = runif(n = 100, min = -122.49, max = -122.38),
lat = runif(n = 100, min = 37.69, max = 37.813))
# Get a map
map <- get_map(location = c(left = -122.523, bottom = 37.69,
right = -122.35, top = 37.8),
maptype = "roadmap", source = "google", color = "bw")
# Plot the points and draw the segments on the map.
ggmap(map) +
geom_point(data = mydf2,
aes(x = lon, y = lat), color = "red", alpha = 0.6, size = 2) +
geom_segment(data = mydf,
aes(x = lon_1, y = lat_1, xend = lon_2, yend = lat_2),
color = "green", size = 2, alpha = 0.8, lineend = "round")
#> Warning: Removed 34 rows containing missing values (geom_point).
Created on 2018-03-25 by the reprex package (v0.2.0).
Adding coordinates as points to a map in R
You need to reproject these points, then you can use standard geom_point
and geom_text
. Your points are far too close together to see them all separately on a world map though:
df <- sf::sf_project("+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0",
"+proj=moll", df) %>%
as.data.frame() %>%
setNames(c("long", "lat")) %>%
cbind(object = object)
world %>%
st_transform(crs = "+proj=moll") %>%
ggplot() +
geom_sf() +
theme_minimal() +
geom_point(data = df, aes(long, lat)) +
geom_text(data = df, aes(long, lat, label = object),
vjust = c(1, 0, -1), hjust = 1)
If you zoom it, it is much clearer:
world %>%
st_transform(crs = "+proj=moll") %>%
ggplot() +
geom_sf() +
theme_minimal() +
geom_point(data = df, aes(long, lat)) +
geom_text(data = df, aes(long, lat, label = object),
vjust = c(0.5, 1, -1), hjust = 1.2) +
coord_sf(ylim = c(4200000, 4700000), xlim = c(-10.75, -10.25) * 10^6)
using ggmap to plot points randomly distributed within boundaries of shape file
Ok, I sorted it out. The solution is in spsample() in package "raster".
d<-data.frame(id=NA,x=NA,y=NA)
l<-data.frame(id=154,n=10)
for (i in unique(l$id)){
temp<-spsample(kommune[which(kommune$OBJECTID==i),],n=l[l$id==i,"n"],type="random")
temp<-as.data.frame(temp)
temp$id<-i
d<-rbind(d,temp[,c("id","x","y")])
}
d<-d[-1,] #drop the first empty row
ggmap(map, extent = "normal", maprange = T)+
geom_polygon(data = dat,
aes(long, lat, group = group),
fill = "blue", colour = "yellow", alpha = 0.1)+
geom_point(aes(x = x, y = y), data = d[which(d$id==154),], alpha = .9,show.legend = T)
Producing a map for each location row using ggmap
We can loop through the data frame to produce one map per row:
library(ggmap)
p <- vector("list", 3)
for (i in seq_along(df)){
p[[i]] <- ggmap(get_map(location = c(lon = df$lon[i], lat = df$lat[i]),
zoom = 12, color = "bw", source = "google")) +
geom_point(data=df[i,], aes(x=long, y=lat), color='red')
}
> p[[1]]
> p[[2]]
> p[[3]]
Notes:
- You had
zoom = 12, ... source = "osm"
inside thelocation = c(...)
argument. These should be arguments forget_map()
. - For some reason I got an error with openstreetmap (HTTP status was '400 Bad Request'), so I used the default google maps instead.
Improving a location visibility using ggmap function in R
Finding the map by address is convenient, but there is more control if you use the longitude/latitude
map <- get_map(location = c(mean(d$lon), mean(d$lat)), zoom = 13, maptype = "satellite", source = "google")
ggmap(map)+
geom_point(data = d, aes(x = lon, y = lat))+
geom_path(data = d, aes(x = lon, y = lat))
ggmap has already set the x and y scales, so you will get warnings if you try to replace them.
Related Topics
Extract Text from Two-Column PDF with R
How to Display a Busy Indicator in a Shiny App
How to Ignore Case When Using Str_Detect
Plotly as Png in Knitr/Rmarkdown
Automating Version Increase of R Packages
Producing Subscripts in R Markdown
What Does ..Level.. Mean in Ggplot::Stat_Density2D
Copying and Modifying a Default Theme
Odds Ratios Instead of Logits in Stargazer() Latex Output
Running Cor() (Or Any Variant) Over a Sparse Matrix in R
How Exactly Does R Parse '->', the Right-Assignment Operator
How to Specify (Non-R) Library Path for Dynamic Library Loading in R
Grid Line Consistent with Ticks on Axis
Error: Zipping Up Workbook Failed When Trying to Write.Xlsx
How to Preserve Transparency in Ggplot2
Weird As.Posixct Behavior Depending on Daylight Savings Time
Define All Functions in One .R File, Call Them from Another .R File. How, If Possible