问题
I am trying to add points to a world map and color them. I have longitude and latitude information for each point, but somehow the outcome points are positioned in a wrong place in the map. It has to be something with the map projection I am using. This are some of the points ('locations') I am trying to add to the world map:
longitude latitude subspecies
-54.8706 -67.4208 red
-53.8057 -67.6862 red
-53.9433 -67.4866 red
-54.4833 -69.6666 red
-54.3833 -66.5666 red
-54.7333 -65.2 red
-53.2333 -68.2 red
-54.2666 -66.7333 red
-52.7166 -68.5333 red
-54.4 -66.55 red
-52.08 -68.6012 red
-54.2166 -66.8666 red
-53.4 -68.0666 red
-53.3 -68.2 red
-35.2141 -75.516 blue
-35.5656 -75.4556 blue
-35.8177 -75.5352 blue
-36.2046 -75.7549 blue
-36.467 -75.8373 blue
-36.7096 -75.9115 blue
...
And this is my code:
locations <- read.csv(file = "stranded_location.csv", header = T)
map <- ggplot() + coord_fixed() + xlab("") + ylab("")
base_world_messy <- map +
geom_polygon(data=world_map, aes(x=long, y=lat, group=group),
colour="grey21", fill="grey21")
base_world_messy
map_data_locations <- base_world_messy +
geom_point(data=locations,
aes(x=longitude, y=latitude), colour=locations$subspecies,
fill=locations$subspecies, pch=21, alpha=I(0.7))
map_data_piloto
Hope to solve this soon. Thanks for your time!
回答1:
I think I found the problems: 1. your latitude & longitude seemed to be reversed, and 2. for the blue subspecies, your y values seemed to have the opposite sign as they should. I did a little dplyr
ing to change the names of those variables to swap the coordinates, and changed the sign of blue y values. Is this what you expect it to look like?
library(tidyverse)
locations <- "longitude latitude subspecies
-54.8706 -67.4208 red
-53.8057 -67.6862 red
-53.9433 -67.4866 red
-54.4833 -69.6666 red
-54.3833 -66.5666 red
-54.7333 -65.2 red
-53.2333 -68.2 red
-54.2666 -66.7333 red
-52.7166 -68.5333 red
-54.4 -66.55 red
-52.08 -68.6012 red
-54.2166 -66.8666 red
-53.4 -68.0666 red
-53.3 -68.2 red
-35.2141 -75.516 blue
-35.5656 -75.4556 blue
-35.8177 -75.5352 blue
-36.2046 -75.7549 blue
-36.467 -75.8373 blue
-36.7096 -75.9115 blue " %>%
read_table2() %>%
# there are stray whitespaces coming in when I copy & paste from SO, so need to delete extra column
select(-X4)
world_map <- map_data("world")
locations %>%
# need to swap longitude & latitude
# changing the names of longitude & latitude to x & y just for clarity
rename(x = latitude, y = longitude) %>%
# somehow blue points have y values flipped
mutate(y = ifelse(subspecies == "blue", y * -1, y)) %>%
ggplot() +
geom_polygon(aes(x = long, y = lat, group = group), data = world_map, fill = "grey21", color = "grey21") +
geom_point(aes(x = x, y = y, color = subspecies)) +
scale_color_identity() +
coord_fixed() +
xlab("") +
ylab("")
Created on 2018-04-17 by the reprex package (v0.2.0).
来源:https://stackoverflow.com/questions/49865235/how-to-add-long-lat-points-in-world-map-with-r