I have a csv file with variables name "Latitude","Longitude","PM10 concentration". You can download data here. I want to plot PM10 data on a map of South Korea according to their latitude and Longitude. Also I want to show them as bubble with different size and color.
Following this example I have already plotted PM10 data on Google Map. But now I want do this without using Google map rather by creating spatial object or in any other way.
I tried to write some code but I have download the spatial data for administration area (GADM) of South Korea. But I am not sure that approach is right or wrong.
library(rgdal)
library(ggplot2)
library(maptools)
map<-readOGR('D:/BACKUP/R/GSTAT/R File/shape file korea map',layer ='KOR_adm2')
summary(kmap)
EPSG<-make_EPSG()
EPSG[grepl("WGS 84$", EPSG$note), ]
kmap84<-spTransform(kmap, CRS("+init=epsg:4326"))
kmaps<-fortify(kmap84)
I don't understand what should I do next.
Here's an example:
library(raster)
library(ggplot2)
download.file("https://docs.google.com/uc?id=0ByY3OAw62EShakxJZkplOXZ0RGM&export=download", tf <- tempfile(fileext = ".csv"))
df <- read.csv(tf, row.names = 1)
skorea <- getData("GADM", country = "South Korea", level = 2)
skorea <- fortify(skorea)
ggplot() +
geom_map(data = skorea, map = skorea, aes(x = long, y = lat, map_id = id, group = group),
fill = NA, colour = "black") +
geom_point(data = df, aes(x = LON, y = LAT, size = PM10), colour = "red", alpha = .5) +
scale_size(range = c(1, 5))
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:
I want to show 15 mile radius circles around points in a map using gBuffer. As far as I can tell I have the points and the map in the same projection, but when I produce the circles on the map, they are too large. Here is my code. The tigerline files for the state and counties can be found at https://www.census.gov/cgi-bin/geo/shapefiles/index.php.
library(tidyverse)
library(rgdal)
library(rgeos)
library(ggplot2)
state <- readOGR('C:\\Users\\Mesonet\\Desktop\\map_folder\\tl_2020_us_state\\tl_2020_us_state.shp')
state <- state[which(state$STATEFP == '46'),]
state <- spTransform(state, CRS("+init=epsg:3857"))
counties <- readOGR('C:\\Users\\Mesonet\\Desktop\\map_folder\\tl_2020_us_county\\tl_2020_us_county.shp')
counties <- counties[which(counties$STATEFP == '46'),]
counties <- spTransform(counties, CRS("+init=epsg:3857"))
sites <- data.frame(Lon = c(-98.1096,-98.27935), Lat = c(43.9029, 43.717258))
coordinates(sites) <- ~Lon + Lat
proj4string(sites) <- CRS("+proj=longlat")
sites <- spTransform(sites, CRS = CRS("+init=epsg:3857"))
# Miles to meters conversion
mile2meter <- function(x){x * 1609.344}
# Buffer creation
site_buffer <- gBuffer(sites, width = mile2meter(15))
png('C:\\Users\\Mesonet\\Desktop\\map_folder\\new_test.png', height = 3000, width = 42*100, res = 100)
ggplot() + geom_path(counties, mapping = aes(x = long, y = lat, group = group), size = 1.75,
alpha = 0.45, col = 'darkgreen') + geom_path(state, mapping = aes(x = long, y = lat, group =
group), size = 0.8) + theme(axis.text = element_blank()) + geom_polygon(site_buffer, mapping
= aes(x = long, y = lat, group = group), fill = '#0000FF', alpha = 1, size = 2)
dev.off()
These two locations are 15.35 miles apart, but the plot shows two circles that overlap each other by a couple miles. I can't figure out why, since from what I can see everything is in the same projection, but I might be wrong. Thank you.
Is it possible to use ggplot2 / ggmap to plot geom_points randomly within a given spatial area defined by a shapefile?
I considered geom_jitter, however I need the plots to be randomly distributed and not cross spatial borders.
Sample data shamelessly borrowed from #matthiash here.
library(rgdal)
library(ggmap)
# Get shapefile with Drammen municipality borders
tmpzip<-tempfile()
tmpdir<-tempfile()
dir.create(tmpdir)
download.file("http://www.kartverket.no/Documents/Kart/N50-N5000%20Kartdata/33_N5000_shape.zip",tmpzip)
unzip(tmpzip, exdir=tmpdir)
kommune <- readOGR(dsn=tmpdir, layer="NO_AdminOmrader_pol")
kommune<-kommune[kommune$NAVN=="Drammen",]
kommune<-spTransform(kommune, CRS("+init=epsg:4326"))
dat<-fortify(kommune)
#get the base map
map <- get_map(location = "Drammen",
maptype = "watercolor", source = "stamen", zoom = 11)
Below code plots the base map with region id 154 from the shapefile plotted on top.
ggmap(map, extent = "normal", maprange = TRUE)+
geom_polygon(data = dat,
aes(long, lat, group = group),
fill = "orange", colour = "red", alpha = 0.2)
What I'd like to do is plot 10 points randomly within the shapefile region defined by dat$id==154
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)
I'm trying to plot a map small multiples grid that shows hurricanes/tropical storms that have intersected with Florida since 1900. I used some spatial queries to subset the database of all Atlantic storms for this project.
I'm now plotting a line shapefile of my limited number of hurricane tracks on top of polygons of the state of Florida, some contiguous states, a few major cities in Florida and, of course, Lake Okeechobee. Here's the simple code:
library(maptools)
library(gdata)
library(RColorBrewer)
setwd("~/hurricanes")
# read shapefiles
florida <- readShapePoly("florida.shp")
south <- readShapePoly("south.shp")
hurricanes <- readShapeLines("hurricanes-florida.shp")
cities <- readShapePoints("cities.shp")
lakes <- readShapePoly("lakes.shp")
# miami, orlando and tallahassee (in FL)
cities <- subset(cities, ST == "FL")
# don't need ALL the 'canes
hurricanes1900 <- subset(hurricanes, Season >= 1900)
mycolors <- brewer.pal(5, "YlOrRd")
pdf(file = "hurricanemaps.pdf", ,width=8,height=20)
par(mfrow=c(15,5), mar=c(1,1,1,1))
for(i in 1:nrow(hurricanes1900))
{
plot(south, col="#e6e6e6", border = "#999999")
plot(florida, col="#999999", border = "#999999", add = TRUE)
plot(lakes, col="#ffffff", border = "#999999", add = TRUE)
plot(cities, pch=10, cex=.1,col="#000000", bg="#e38d2c", lwd=1, add = TRUE)
plot(hurricanes1900[i,], col = mycolors[cut(hurricanes$MAX_Wind_W, breaks = 5)],
lwd=3, add = TRUE); title(hurricanes1900$Title[i])
}
dev.off()
Three big issues I'm encountering:
1) The loop is giving me a map of each storm. I would prefer to have the code produce a Florida/South map in the grid for each year (even on those years without storms) and all the storms for that year, preferably with labels.
2) I would like to set the colors for wind speed among ALL the storms, not just those in each particular row of the loop. That way strong storms (like Andrew in 1992) show as darker even when they are the only storm of the year. Perhaps I can solve this my recoding a categorical (H1, H2, etc) variable that can be styled accordingly.
3) Assuming I can figure out No. 1, I'm having trouble getting labels to render on each storm path. The maptools documentation isn't great.
Anyway, here's the output so far (the title is a concatenation of two fields in the shapefile):
The real issue is No. 1. Thanks in advance for your help.
Given there is no reproducible data, I collected some data for this demonstration. Please provide a minimal reproducible data for SO users from next time. That will help you receive more help.
What you want to achieve can be done with ggplot2. If you want to draw a map for each year, you can use facet_wrap(). If you want to add colors based on wind, you can do that in aes() when you draw paths. If you want to add hurricanes' names, you can use the ggrepel package, which allows you to provide annotations with an ease. Note that, if you want to draw smooth paths, you further need data process.
library(stringi)
library(tibble)
library(raster)
library(ggplot2)
library(ggthemes)
library(ggrepel)
library(RColorBrewer)
library(data.table)
# Get some data. Credit to hmbrmstr for a few lines in the following code.
mylist <- c("http://weather.unisys.com/hurricane/atlantic/2007H/BARRY/track.dat",
"http://weather.unisys.com/hurricane/atlantic/2007H/TEN/track.dat",
"http://weather.unisys.com/hurricane/atlantic/2006H/ERNESTO/track.dat",
"http://weather.unisys.com/hurricane/atlantic/2006H/ALBERTO/track.dat")
temp <- rbindlist(
lapply(mylist, function(x){
foo <- readLines(x)
foo <- read.table(textConnection(gsub("TROPICAL ", "TROPICAL_",
foo[3:length(foo)])),
header=TRUE, stringsAsFactors=FALSE)
year <- stri_extract_first(str = x, regex = "[0-9]+")
name <- stri_extract_first(str = x, regex = "[A-Z]{2,}")
cbind(foo, year, name)
}
))
### Add a fake row for 2017
temp <- temp %>%
add_row(ADV = NA, LAT = NA, LON = NA, TIME = NA, WIND = NA,
PR = NA, STAT = NA, year = 2017, name = NA)
### Prepare a map
usa <- getData('GADM', country = "usa", level = 1)
mymap <- subset(usa, NAME_1 %in% c("Florida", "Arkansas", "Louisiana",
"Alabama", "Georgia", "Tennessee",
"Mississippi",
"North Carolina", "South Carolina"))
mymap <- fortify(mymap)
# Create a data.table for labeling hurricanes later.
label <- temp[, .SD[1], by = name][complete.cases(name)]
g <- ggplot() +
geom_map(data = mymap, map = mymap,
aes(x = long, y = lat, group = group, map_id = id),
color = "black", size = 0.2, fill = "white") +
geom_path(data = temp, aes(x = LON, y = LAT, group = name, color = WIND), size = 1) +
scale_color_gradientn(colours = rev(brewer.pal(5, "Spectral")), name = "Wind (mph)") +
facet_wrap(~ year) +
coord_map() +
theme_map() +
geom_text_repel(data = label,
aes(x = LON, y = LAT, label = name),
size = 2,
force = 1,
max.iter = 2e3,
nudge_x = 1,
nudge_y = -1) +
theme(legend.position = "right")
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')