I keep getting this error when trying to make a map...
Error in geom_map(data = all_states, map = all_states, mapping = aes(map_id = State, :
all(c("x", "y", "id") %in% names(map)) is not TRUE
My code so far...
all_states = read.csv(file = "https://public.opendatasoft.com/explore/dataset/us-zip-code-latitude-and-longitude/download/?format=csv&timezone=America/New_York&use_labels_for_header=true",
header = TRUE,
sep = ";")
all_states$State = state.name[match(all_states$State, state.abb)]
all_states = na.omit(all_states)
ggplot(data = all_states, aes(map_id = State)) +
geom_map(data = all_states,
map = all_states,
mapping = aes(map_id=State,x=Longitude,y=Latitude)) +
coord_fixed()
What am I doing wrong?
2 Problems.
You did not download the correct map. geom_map needs data for creating polygons, but your data contains the coordinates for cities
geom_map is very peculiar and restrictive about column names in data frames
Solution
get the right map (e.g., Just use the maps package for US)
rename the columns
I have also removed one or two lines and 'fortified' the data frame, as this is usually recommended before using it for maps.
library(tidyverse)
all_states = read.csv(file = "https://public.opendatasoft.com/explore/dataset/us-zip-code-latitude-and-longitude/download/?format=csv&timezone=America/New_York&use_labels_for_header=true", header = TRUE, sep = ";")
all_states = na.omit(all_states) %>%
mutate(region = State, long=Longitude, lat = Latitude) %>%fortify
US <- map_data('usa')
#>
#> Attaching package: 'maps'
#> map
ggplot()+
geom_map(data = US, map = US, mapping = aes( map_id = region, x = long, y = lat), fill = 'white') +
# now this is the US background
geom_point(data = filter(all_states, ! region %in% c('HI','AK','AS')), aes(x = long, y = lat), size = .01, color = 'black')
# and this is YOUR data. Use geom_point for it!!!
#I have removed Alaska, Hawaii and a third little bit which I ignorantly don't know. 'AS'.
#> Warning: Ignoring unknown aesthetics: x, y
Created on 2019-08-02 by the reprex package (v0.2.1)
Related
I'm using the Taiwan housing data found on UCI ML repository.
I'm trying to plot the houses on a map using ggplot, and fill the points with the house_price_unit_area. However, when I use fill = house_price_unit_area in the aesthetic call, it doesn't fill the points based on price, but rather it leaves them black.
Any suggestions on how to fix this? Code included below, as well as a screenshot of what is produced.
library(ggplot)
library(ggmap)
library(readxl)
df <- read_xlsx("data/real_estate.xlsx")
df$No = NULL
colnames(df)= c("trans_date",
"house_age",
"distance_to_nearest_mrt",
"number_of_conv_store",
"lat",
"long",
"house_price_unit_area",
"id")
world <- map_data(database = "world", regions = "Taiwan")
ggmap(get_stamenmap(bbox = c(left = 121.4, right = 121.64, bottom=24.9,top=25.1),location = "Taiwan"))+
geom_point(data =df, mapping = aes(x=long,y=lat, fill = house_price_unit_area))+
scale_fill_viridis_b()
I switch the fill argument for col and got this:
library(ggplot)
library(ggmap)
library(readxl)
df <- read_xlsx("Real estate valuation data set.xlsx")
df$No = NULL
colnames(df)= c("trans_date",
"house_age",
"distance_to_nearest_mrt",
"number_of_conv_store",
"lat",
"long",
"house_price_unit_area",
"id")
world <- map_data(database = "world", regions = "Taiwan")
ggmap(get_stamenmap(bbox = c(left = 121.4, right = 121.64, bottom=24.9,top=25.1),location = "Taiwan"))+
geom_point(data =df, mapping = aes(x=long,y=lat, col = house_price_unit_area))+
scale_fill_viridis_b()
output:
Data: https://github.com/yuliaUU/data/blob/main/test.csv
griddf <- read_csv("test.csv")
create a map:
world <- rnaturalearth::ne_countries(scale = "medium", returnclass = "sf") # add continents
ggplot()+
geom_tile(data = Data |> dplyr::filter(Model.1=="RF"), aes(x = Lon, y = Lat, fill= value/1000))+geom_sf(data=world)+
viridis:: scale_fill_viridis(option = "H", na.value = NA) +
labs(fill="Probability")+
facet_wrap(~ Model.1)
My issue is that it creates a map with "lines" which I do not understand why. I know it has something to do with irregular grid I am using ( all grid cell should be equal area)
and when I add different projection:
+ coord_sf(crs = '+proj=moll')
I get nothing plotted
You basically answered the question yourself - your data is too granular. For a more "complete" look, you might want to 2d-interpolate the values. Here, I am using akima::interp, but there are other functions out there - this is not the place to discuss which is the best to use.
library(ggplot2)
griddf <- read.csv(url("https://raw.githubusercontent.com/yuliaUU/data/main/test.csv"))
world <- rnaturalearth::ne_countries(scale = "medium", returnclass = "sf") # add continents
val_interpol <- with(griddf, akima::interp(Lon, Lat, value, xo = -180:180, yo = -90:90))
#> Warning in akima::interp(Lon, Lat, value, xo = -180:180, yo = -90:90): collinear
#> points, trying to add some jitter to avoid colinearities!
#> Warning in akima::interp(Lon, Lat, value, xo = -180:180, yo = -90:90): success:
#> collinearities reduced through jitter
## thanks Akrun https://stackoverflow.com/q/58123551/7941188
## matrix doesn't allow negative values for subsetting
d1 <- expand.grid(x = 1:361, y = 1:181)
out <- transform(d1, z = val_interpol$z[as.matrix(d1)])
out$x <- out$x-181
out$y <- out$y-91
ggplot()+
geom_raster(data = out , aes(x = x, y = y, fill= z), interpolate = TRUE)+
geom_sf(data=world)+
labs(title=paste0("Swordfish Probability of Occurance"),
x="", y="", subtitle="data from 2000-present (0.5x0.5 grid)")+
viridis:: scale_fill_viridis(option = "H", na.value = "black")
Created on 2022-05-06 by the reprex package (v2.0.1)
I tried to get Berlin map from OpenStreetMap and then plot some locations on it (they should look like points, not markers).
I got the map based on the data I have cause I don't want a whole map, but area where includes all locations. However when I plot the points on the map, it delivers an error message:
non-numeric argument to binary operator
My code:
library(ggplot2)
library(OpenStreetMap)
# creating a sample data.frame with lat/lon points
lon <- read.csv("Data.csv", header = TRUE, colClasses=c("NULL", "NULL", NA))
lat <- read.csv("Data.csv", header = TRUE, colClasses=c("NULL", NA, "NULL"))
df <- as.data.frame(cbind(lon,lat))
# getting the map
mapberlin <- openmap(c(max(lat)+0.03,min(lon)-0.03), c(min(lat)-0.03,max(lon)+0.03), zoom = NULL,type = 'osm')
# plotting the map with some points on it and draw line between points
plot(mapberlin) + geom_point(data = df, aes(x = lon, y = lat, fill = 'red'), size = 2, shape = 21)
+geom_line(data = df, aes(x = lon, y = lat), color = 'blue') +
+guides(fill=FALSE, size=FALSE)
I have already generated a simple map for Nigerian states, and now I would like to highlight in my map the borders for the Nigerian regions (that group Nigerian states).
When I add the layer for the borders with geom_polygon, they appear lines that do not correspond to region borders. I found a similar problem here Map county borders on to a ggmap
but this does not seem to be working for my case.
Here are the shapefiles and the database I am working on:
https://www.dropbox.com/sh/cek92s50jixowfx/AABwIVZKvtff8-9slhfCbxEca?dl=0
The code I am using is
#LOAD SHAPEFILES AND DATABASE
ng_dist <- readShapeSpatial("NGA_adm1.shp")
ng_dist_regions <- readShapeSpatial("NGA_adm_Region.shp")
NG_States <- read.csv("State_color_map.csv", header = TRUE, sep=",")
#VERIFY THE MAPS LOADED PROPERLY
plot(ng_dist)
plot(ng_dist_regions)
# STATE MAP - fortify and match shapefile and database IDs names
intersect(ng_dist$NAME_1, NG_States$STATE)
ng_dist <- fortify(ng_dist, region = "NAME_1")
ng_dist$id[which(ng_dist$id == "Akwa Ibom")] <- "Akwa-ibom"
ng_dist$id[which(ng_dist$id == "Nassarawa")] <- "Nasarawa"
ng_dist$id[which(ng_dist$id == "Cross River")] <- "C/river"
ng_dist$id[which(ng_dist$id == "Federal Capital Territory")] <- "FCT"
intersect(ng_dist$id, NG_States$STATE)
# REGION MAP - fortify
ng_dist_regions <- fortify(ng_dist_regions, region = "Region")
### Convert dummy variable to factor
NG_States$Abia <- as.factor(NG_States$Abia)
#PLOT MAP with coloured Abia State
cols <- c("0" = "#e6e6e6","1" = "#6eab27")
ABIA <- NG_States$Abia
Abia_map <- ggplot(NG_States, aes(fill = ABIA)) +
geom_map(data = NG_States, aes(map_id = NG_States$STATE, fill = ABIA), map = ng_dist, color = "black", size = 0.10) +
expand_limits(x = ng_dist$long, y = ng_dist$lat) +
theme_nothing(legend = FALSE) +
labs(title="Abia") +
coord_map() +
scale_fill_manual(name="", values=cols, labels=c("","Abia"))
Abia_map
#Add layer for region borders
d <- Abia_map +
geom_polygon(aes(x = ng_dist_regions$long, y = ng_dist_regions$lat, group = ng_dist_regions$id, fill = NA), data = ng_dist_regions, color = "red", size = 0.8)
d
Here is my result
Nigerian States and Regions
I have tried to add other options, such as coord_fixed() or expand_limits(x = ng_dist_regions$long, y = ng_dist_regions$lat), but I am quite basic R user and I don't know other solutions.
Using group, instead of id as group seems to solve the problem.
d <- Abia_map +
geom_path(aes(x = long, y = lat, group = group), data = ng_dist_regions, color = "red", size = 0.8, inherit.aes = FALSE)
d
I want to plot different states of India with respective districts in R software. I have tried using GADM, level 2 data to get the coordinates.
I have followed this thread Mapping just one State of India and writing its name inside the state boundary. However, I am unable to subset the data for any state and use it for mapping.
What I've tried:
map <- fortify(Karnataka)
map$id <- as.integer(map$id)
dat <- data.frame(id = 216:242, district = Karnataka)
map_df <- inner_join(map, dat, by = "id")
centers <- data.frame(gCentroid(Karnataka, byid = TRUE))
centers$state <- dat$district
I could map a state with its district borders by using following commands.
India <- getData("GADM", country = "India", level = 2)
Karnataka <- subset(India, NAME_1 == "Karnataka")
map <- fortify(Karnataka);
map$id <- as.integer(map$id);
dat <- data.frame(id = 216:242, district = Karnataka#data$NAME_2);
map_df <- inner_join(map, dat, by = "id");
centers <- data.frame(gCentroid(Karnataka, byid = TRUE));
centers$state <- dat$district;
ggplot() +
geom_map(data = map_df, map = map_df,
aes(map_id = id, x = long, y = lat, group = group),
color = "#ffffff", fill = "#bbbbbb", size = 0.25) +
geom_text(data = centers, aes(label = state, x = x, y = y), size = 2) +
coord_map() + labs(x = "", y = "", title = "Districts of Karnataka")
You can do this beautifully and easily with Google Maps in R. Within ggmap there are a lot of options. The examples below are very basic but it's fully customizable by setting the options however you like them.
map <- qmap('Karnataka', zoom = 7, maptype = 'hybrid')
map
library(ggmap)
qmap('Karnataka')