I am trying to plot out a base map of Illinois by counties.
Libraries I had loaded:
library(ggplot2)
library(maps)
library(ggmap)
library(mapdata)
This is my code:
states <- map_data("state")
IL <- subset(states, region %in% c("illinois"))
counties <- map_data("county")
IL_county <- subset(counties, region == "illinois")
il_base <- ggplot(data = IL, mapping = aes(x = long, y = lat)) +
coord_fixed(1.3) +
geom_polygon(color = "black", fill = NA) +
theme_nothing()
il_base
il_base +
geom_polygon(data = IL_county, fill = NA, color = "black") +
geom_polygon(color = "black", fill = NA)
The il_base plot is fine, it shows a basic outline of the state. However, as soon as I add geom_polygon to this it maps the counties out like this:
And this is NOT what the counties of IL look like. What did I do wrong here?
I solved the problem by modifying the base plot to:
# Add group
il_base <- ggplot(data = IL, mapping = aes(x = long, y = lat, group = group)) +
coord_fixed(1.3) +
geom_polygon(color = "black", fill = NA) +
theme_nothing()
Related
I am trying to incorporate labels of provinces, and cities with labels and dots into a South African map.I can get a map with provincial subdivisions from a spdf file, from website https://gadm.org/download_country_v3.html
SA1spdf <- readRDS("gadm36_ZAF_1_sp.rds")
And I am trying to use the information in the slot:
SA1spdf#data#ADM1_EN
that contains the label of the 9 provinces
I want to place the labels in the center of the polygons, if possible, so I got the centroids of the 9 provinces:
centroids_SAdf <- as.data.frame(coordinates(SA1spdf))
and change names V1 and V2 to Longitude and Latitude
names(centroids_SAdf) <- c("Longitude", "Latitude")
Also I want to add a few cities to the plot:
coordinates_cities <- data.frame(city = c("Cape Town", "Durban", "Johannesburg", "Port Elizabeth"),lat = c(-33.930, -29.870, -26.190, -33.960 ), lon = c(18.460, 30.990, 28.040,25.590 )
but I cannot link all these together.
I can get a map with:
qtm(SA1spdf, fill = "white")
Using maptools and the following codes all return error messages
qtm(SA1spdf, fill = "white") + tm_text("SA1spdf$data#ADMN1_EN")
tm_shape(SA1spdf) + tm_polygons() + tm_fill(col = "white")
I dont get a white filled map, its filled with grey colour
the following codes return error messages:
tm_shape(SA1spdf) + tm_polygons() + tm_text(c("Eastern Cape","Free State" , "Gauteng","KwaZulu-Natal", "Limpopo","Mpumalanga","North West","Nothern Cape","Western Cape"))
ggplot(SA1spdf, aes(x = lon, y = lat), group = group) + geom_polygon(fill = "white") + geom_point(data = coordinates_cities, aes(x = lat, y = lon)) + geom_text(data= coordinate_cities, aes(label = city))
library(sp)
library(ggplot2)
library(tmap)
library(rgeos)
I'll use the same object SA1spdf you created with data from ZAF as sp object from GADM
coordinate_cities <- data.frame(
city = c("Cape Town", "Durban", "Johannesburg", "Port Elizabeth"),
lat = c(-33.930, -29.870, -26.190, -33.960),
long = c(18.460, 30.990, 28.040,25.590))
base plot
plot(SA1spdf)
points(coordinate_cities$lon, coordinate_cities$lat, pch = 16, col = "red", cex = 1)
text(coordinate_cities$lon, coordinate_cities$lat, coordinate_cities$city, adj = c(0, 0), cex = 0.7)
title(main = "South Africa", sub = "Main cities")
ggplot2
sa_df <- fortify(SA1spdf)
#> Regions defined for each Polygons
ggplot(sa_df, aes(long, lat)) +
geom_polygon(aes(group = group), fill = "white", colour = "black") +
geom_point(data = coordinate_cities, aes(x = long, y = lat), colour = "red") +
geom_text(data = coordinate_cities, aes(label = city), vjust = -1) +
coord_equal()
tmap
# convert coordinate_cities to sp object
sa_cities_spdf <- SpatialPointsDataFrame(coords = coordinate_cities[, c("long", "lat")],
data = coordinate_cities[, "city", drop = FALSE],
proj4string = CRS("+proj=longlat +datum=WGS84"))
tm_shape(SA1spdf) +
tm_borders() +
tm_layout(main.title = "South Africa regions") +
tm_text("NAME_1", size = 0.7) +
tm_shape(sa_cities_spdf) + tm_symbols(size = 0.5, col = "red")
Created on 2021-06-17 by the reprex package (v0.3.0)
I plotted some data points on a map. The Map is the bounty King in Washington. I plotted them on the map successfully. My dataset consists of a column called prices. Their values range in between 0-800000.
I created a new column, called MapColor to print the value either as red or blue based on the price value. If price> 400000 red, else blue.
Now when plotting the points in the map, if MapColor is red I need to map it as red points and if not black. This is how I tried it. But the colors are plotting black only. This is what I tried
long <- c(47.5112,47.7210 ,47.3684)
lat <- c(-122.257, -122.319, -122.031)
price <- c(287655,456355,662500,234563)
House <- data.frame(long, lat, price)
House$MapColor <- ifelse(House$price >=400000, "red", "black")
col <- as.character(House$MapColor)
states <- map_data("state")
wa_df <- states %>%
filter(region == "washington", subregion == 'king')
counties <- map_data("county")
wa_county <- counties %>%
filter(region == "washington")
wa_base <-
ggplot(data = wa_df,
mapping = aes(x = long, y = lat, group = group)) + geom_point(data = House,aes(x = long, y = lat),size = 0.5,inherit.aes = FALSE) +
coord_fixed(1.3) +scale_color_manual(values=col)+
geom_polygon(color = "black", fill = "gray")
#geom_point(data = House, mapping = aes(x = long, y = lat), color = "red")
wa_base + theme_nothing() +
geom_polygon(data = wa_county, fill = NA, color = "black") +
geom_polygon(color = "black", fill = NA) # get the state border back on top
Please let me know if this is what you had in mind.
I think long and lat for those example points were reversed. I set the colors as either red or blue as per the description.
It maps the state polygon, then county, then adds the points using color = House$MapColor.
library(ggplot2)
library(ggmap)
lat <- c(47.5112, 47.7210, 47.3684)
long <- c(-122.257, -122.319, -122.031)
price <- c(287655, 456355, 662500)
House <- data.frame(long, lat, price)
House$MapColor <- ifelse(House$price >= 400000, "red", "blue")
wa_df <- map_data("state") %>%
filter(region == "washington")
wa_county <- map_data("county") %>%
filter(region == "washington")
ggplot(data = wa_df, mapping = aes(x = long, y = lat, group = group))+
geom_polygon(color = "black", fill = NA)+
geom_polygon(data = wa_county, fill = NA, color = "black")+
geom_point(data = House, mapping = aes(x = long, y = lat), color = House$MapColor)+
coord_fixed(1.3)+
theme_nothing()
I came up with a way to plot rivers using geom_path. I do not know if there is a better way. I had to split the dataframe into hundreds of "rivers". So it is very slow. Any ideas?
world_map <- map_data('world')
system("wget https://sites.google.com/site/joabelb/Home/PrincRiosBrazil.zip")
system("unzip -o PrincRiosBrazil.zip")
library(rgdal)
shapeHid <- readOGR(dsn = ".", layer = "PrincipaisRiosDoBrasil")
shapeHid#data$id = rownames(shapeHid#data)
library(ggplot2)
shapeHid.points = fortify(shapeHid, region="id")#
shapeHid.df = merge(shapeHid.points, shapeHid#data, by="id", all=F)
listofrivers<-split(shapeHid.df, shapeHid.df$id)
myMap3 <- ggplot() +
lapply(listofrivers, function(x) geom_path(data=x, aes(x=long, y=lat), color="gray70", linetype=1)) +
geom_map(data = world_map, map = world_map, aes(map_id = region),
color = 'black', fill = NA, linetype=2) +
theme(panel.border = element_rect(fill = NA, colour = "black"))+
theme(axis.title=element_blank())+
scale_y_continuous(limits=c(-15,6),expand=c(0,0))+
scale_x_continuous(limits=c(-76,-55),expand=c(0,0))
myMap3
If you routinely work with shapefiles, geom_path and geom_polygon gives everything you need. In recent versions, ggplot deals directly with spatial objects, so there's no need to use fortify and merge (probably the step taking more time in your code). Here's an example using the shapefile of federative units of Brazil from IBGE as base map:
shapeUFs <- readOGR('.', 'BRUFE250GC_SIR')
shapeHid <- readOGR('.', 'PrincipaisRiosDoBrasil')
ggplot(shapeUFs, aes(long, lat, group = group)) +
geom_polygon(fill = 'gray90', color = 'black') +
geom_path(data = shapeHid, color = 'steelblue2') +
coord_map() + theme_void()
Performance will be affected by the size of your shapes (determined by number of features and level of details) more than the geometry you're using in ggplot. You can use rgeos::gSimplify to reduce the number of vertices in a spatial polygon/lines object. You can also plot points directly over the map:
# Simplifying the geometry of the federative units
shapeUFs.s <- rgeos::gSimplify(shapeUFs, .05, TRUE)
# Storing map in an object
riversMap <- ggplot(shapeUFs.s, aes(long, lat)) +
geom_polygon(aes(group = group), fill = 'gray90', color = 'black') +
geom_path(data = shapeHid, aes(group = group), color = 'steelblue2') +
coord_map() + theme_void()
# Sampling 20 cities in Brazil
brMunics <- read.csv('https://raw.githubusercontent.com/kelvins/Municipios-Brasileiros/master/Municipios_Brasileiros.csv')
Munics <- brMunics[sample(nrow(brMunics), 20), ]
# Plotting points over the map
riversMap + geom_point(data = Munics, aes(Longitude, Latitude), color = 'red')
# If your data already have the coordinates named 'lat' and 'long',
# you can skip aes(Longitude, Latitude):
names(Munics)[6:7] <- c('lat','long')
riversMap + geom_point(data = Munics, color = 'red')
I would do the following:
library(sf)
library(ggplot2)
world_map <- map_data('world')
sdf <- read_sf("PrincipaisRiosDoBrasil.shp")
myMap3 <- ggplot() +
geom_map(data = world_map, map = world_map, aes(map_id = region), color = 'black', fill = NA, linetype=2) +
geom_sf(data = sdf)+
theme(panel.border = element_rect(fill = NA, colour = "black"))+
theme(axis.title=element_blank())+
scale_y_continuous(limits=c(-15,6),expand=c(0,0))+
scale_x_continuous(limits=c(-76,-55),expand=c(0,0))
myMap3
You'll need to update ggplot2 to 3.0.0 for geom_sf.
This question already has answers here:
Show the value of a geom_point using geom_text
(2 answers)
Closed 5 years ago.
I have created a world map with the use of the ggplot2 library.
I am attempting to label the two cities (Shanghai and Sao Paulo) respectively through using labels in ggplot2. However, when I try to add labels I get the error message:
Warning: Ignoring unknown aesthetics: labels
Error: geom_text requires the following missing aesthetics: x, y, label
Here is the full code:
require(maps)
require(mapdata)
library(ggplot2)
countries = c("Sao Paulo","Shanghai")
global <- map_data("world")
ggplot() + geom_polygon(data = global, aes(x=long, y = lat, group =
group)) +
coord_fixed(1.3)
ggplot() +
geom_polygon(data = global, aes(x=long, y = lat, group = group),
fill = NA, color = "red") +
coord_fixed(1.3)
gg1 <- ggplot() +
geom_polygon(data = global, aes(x=long, y = lat, group = group),
fill = "green", color = "blue") +
coord_fixed(1.3)
gg1
labs <- data.frame(
long = c(-46.625290,121.4580600),
lat = c(-23.533773,31.2222200),
stringsAsFactors = FALSE
)
gg1 +
geom_point(data = labs, aes(x = long, y = lat), color = "red", size
= 5) + ggtitle("World Map") + geom_text(aes(labels=countries),vjust=0,
colour="red")
Clearly, I'm using ggplot wrong in some way but can't figure out how.
labs$countries <- countries
gg1 +
geom_point(data=labs, aes(long, lat), colour="red", size=5) +
ggtitle("World Map") +
geom_text(data=labs, aes(long, lat, label=countries))
I am wondering how to draw a map using get_map and ggmap of any federal country (i.e. a country with provinces and counties). Any country, other than the US would be great. To make it look nice, fill the geom_polygon of counties (any fill), and provinces are empty polygons, only with its contours. So, basically, it is two overlapping ggmaps.
You can get the shapefiles here:
https://www.dropbox.com/s/4nl685t860x1e8r/municipios_br.zip
rm(list = ls())
library(ggplot2)
library(rgdal)
library(ggmap)
# READ SHAPEFILE OF BOUNDARIES
Map <- readShapePoly("municipios_br.shp")
head(as.data.frame(Map))
Map = gBuffer(Map, width=0, byid=TRUE)
MapC <- fortify(Map, region="CODIGO_MUN") # municipalities
MapP <- fortify(Map, region="CODIGO_UF") # state boundaries
MapC$test <- 1
MapP$test <- 1
MapC <- Map[order(MapC$order),]
MapP <- MapP[order(MapP$order),]
The following code produces counties boundaries:
google.map <- get_map(location = 'Brazil', zoom=4,maptype="terrain")
m0 <- ggmap(google.map)
m1 <- m0 + geom_polygon(color = 'grey90', size = .01, aes(x=long, y=lat, group=group, fill=as.factor(test)), data=MapC, alpha=.6)
m1 + guides(fill=FALSE) + scale_fill_manual(values=c("red"))
Now, provinces:
m2 <- m0 + geom_polygon(color = 'grey50', size = .1, aes(x=long, y=lat, group=group, fill=as.factor(test)), data=MapP, alpha=.9)
m2 + guides(fill=FALSE) + scale_fill_manual(values=c(NA))
How to make the two work together?
You could also get your maps from e.g. GADM:
library(raster)
adm1 <- getData('GADM', country='HUN', level=0)
adm2 <- getData('GADM', country='HUN', level=1)
And let us fortify those for ggplot usage:
library(ggplot2)
fadm1 = fortify(adm1)
fadm2 = fortify(adm2)
And add as many layers and geoms as you wish:
ggplot(fadm1, aes(x = long, y = lat, group = group)) + geom_path() +
geom_polygon(data = fadm2, aes(x = long, y = lat),
fill = "green", alpha = 0.5) +
geom_path(data = fadm2, aes(x = long, y = lat), color = "blue") +
theme_bw()
Resulting in:
Update: combining your two layers mentioned in the updated questions
m0 + geom_polygon(size = .01,
aes(x = long, y = lat, group = group, fill = as.factor('red')),
data = MapC,
alpha = .6) +
geom_path(color = 'grey50', size = .1, aes(x = long, y = lat, group = group),
data=MapP, alpha=.9) +
guides(fill=FALSE)