Plotting 1 attribute of a shp file in R - r

I'm trying to select & plot just one of these 9 attributes from my shape file, but nothing seems to work.
Could you help?
enter image description here

It helps if you make a fully reproducible example so that fixers can run the code and be certain that they have resolved the issue.
Here is an example that you will have to modify for your own needs.
library(sf)
fname <- system.file("shape/nc.shp", package="sf") # read a shape file that comes with the sf package
nc <- st_read(fname)
plot(nc) # plot all the data
plot(nc['AREA']) # plot one of the attributes

Related

Use "st_transform()" to transform coordinates to another projection - when creating cartogram

I have a shapefile of population estimates of different administrative levels on Nigeria and I want to create a cartogram out of it.
I used the cartogram package and tried the following
library(cartogram)
admin_lvl2_cartogram <- cartogram(admin_level2_shape, "mean", itermax=5)
However this gives me an error stating "Error: Using an unprojected map. This function does not give correct centroids and distances for longitude/latitude data:
Use "st_transform()" to transform coordinates to another projection." I'm not sure how to resolve this
To recreate the initial data
Download the data using the wopr package
library(wopr)
catalogue <- getCatalogue()
# Select files from the catalogue by subsetting the data frame
selection <- subset(catalogue,
country == 'NGA' &
category == 'Population' &
version == 'v1.2')
# Download selected files
downloadData(selection)
Manually unzip the downloaded zip file (NGA_population_v1_2_admin.zip) and read in the data
library(rgdal)
library(here)
admin_level2_shape <- readOGR(here::here("wopr/NGA/population/v1.2/NGA_population_v1_2_admin/NGA_population_v1_2_admin_level2_boundaries.shp"))
The function spTransform in the sp package is probably easiest because the readOGR call returns a spatial polygon defined in that package.
Here's a full example that transforms to a suitable projection for Nigeria, "+init=epsg:26331". You'll probably have to Google to find the exact one for your needs.
#devtools::install_github('wpgp/wopr')
library(wopr)
library(cartogram)
library(rgdal)
library(sp)
library(here)
catalogue <- getCatalogue()
# Select files from the catalogue by subsetting the data frame
selection <- subset(catalogue, country == 'NGA' & category == 'Population' & version == 'v1.2')
# Download selected files
downloadData(selection)
unzip(here::here("wopr/NGA/population/v1.2/NGA_population_v1_2_admin.zip"),
overwrite = T,
exdir = here::here("wopr/NGA/population/v1.2"))
admin_level2_shape <- readOGR(here::here("wopr/NGA/population/v1.2/NGA_population_v1_2_admin/NGA_population_v1_2_admin_level2_boundaries.shp"))
transformed <- spTransform(admin_level2_shape, CRS("+init=epsg:26331"))
admin_lvl2_cartogram <- cartogram(transformed, "mean", itermax=5)
I confess I don't know anything about the specific packages so I don't know if what is produced is correct, but at least it transforms.

Extract bands as individual layers from a multilayered tiff file

I have a tiff file which contains 6 bands Data link, I used all methods to extract [See here][2] [see here 2][3] all 6 bands as individual layers but unable to extract them as individual files.
library(raster)
library(ncdf4)
library(rgdal)
r <- raster("E:/TRY/bands.tif")
writeRaster(r, paste0(names(r),".tif"), bylayer=TRUE, format="GTiff")
I get just one tif file and the file doesn't have any information whatsoever like what it is.
Appreciate any help
thanks
Try the function raster::stack. This will read all the layers.
library(raster)
library(ncdf4)
library(rgdal)
s1 <- stack("~/Downloads/bands.tif")
writeRaster(s1, paste0(names(s1),".tif"), bylayer=TRUE, format="GTiff")

Read shape file with readOGR verses readShapePoly

I have read a shapefile using readShapePoly in the maptools package, but cannot read that same file with readOGR. I am hoping someone may be able to help me read the shapefile with readOGR.
I downloaded the file orcounty.shp from here: http://geography.uoregon.edu/geogr/topics/maps.htm
I also downloaded the associated files: orcounty.shx, orcounty.sbx, orcounty.sbn, and orcounty.dbf and put all five files in the folder: c:/users/mark w miller/gis_in_R/shapefile_example/
The following code reads the shapefile and displays some attributes:
library(maptools)
setwd('c:/users/mark w miller/gis_in_R/shapefile_example/')
# Oregon county census data (polygons)
orcounty.poly <- readShapePoly('orcounty.shp', proj4string=CRS("+proj=longlat"))
orcounty.line <- readShapeLines('orcounty.shp', proj4string=CRS("+proj=longlat"))
# see projection
summary(orcounty.poly)
Object of class SpatialPolygonsDataFrame
Coordinates:
min max
x -124.55840 -116.46944
y 41.98779 46.23626
Is projected: FALSE
proj4string : [+proj=longlat]
Data attributes:
However, when I try to read that same shapefile using the following code I receive an error:
library(rgdal)
# read shapefile
oregon.map <- readOGR(dsn="c:/users/mark w miller/gis_in_R/shapefile_example/", layer="orcounty")
# convert to dataframe
oregon.map_df <- fortify(oregon.map)
The error message says:
Error in ogrInfo(dsn = dsn, layer = layer, encoding = encoding, use_iconv = use_iconv) :
Cannot open file
I can read Natural Earth http://www.naturalearthdata.com/ shapefiles using:
library(rgdal)
setwd("c:/users/mark w miller/gis_in_R/")
# read shapefile
wmap <- readOGR(dsn="ne_110m_physical", layer="ne_110m_land")
So, apparently there is a difference between the Natural Earth shapefiles and the Oregon shapefile orcounty.shp.
Thank you for any advice on how to read orcounty.shp with readOGR. My question is similar to the question here: rgdal / readOGR - unable to read shapefile from .zip
Try to remove your last '/' from file path.
readOGR(dsn = 'c:/users/mark w miller/gis_in_R/shapefile_example',
layer = 'orcounty')
For anyone ending up here with this error on a Linux box, I found the problem was using a home path shortcut. i.e.
# Works
readOGR(dsn="/home/user/dir", layer="file")
# Doesn't work
readOGR(dsn="~/dir", layer="file")
I have no idea why.
I used the file ne_110m_land
Try with this:
setwd('D:/JMSR/codes.R/mapas')
unzip("ne_110m_land.zip")
ogrInfo(".", "ne_110m_land")
wmap <- readOGR(".", "ne_110m_land")
raster::shapefile wraps around readOGR to take care of paths and tildes; just pass the full file name.
library(raster)
x <- shapefile("c:/users/orcounty.shp')
or
y <- shapefile("~/users/orcounty.shp")

How to convert .shp file into .csv in R?

I want to to convert two .shp files into one database that would allow me to draw the maps together.
Also, is there a way to convert .shp files into .csv files? I want to be able to personalize and add some data which is easier for me under a .csv format. What I have in mind if to add overlay yield data and precipitation data on the maps.
Here are the shapefiles for Morocco, and Western Sahara.
Code to plot the two files:
# This is code for mapping of CGE_Morocco results
# Loading administrative coordinates for Morocco maps
library(sp)
library(maptools)
library(mapdata)
# Loading shape files
Mor <- readShapeSpatial("F:/Purdue University/RA_Position/PhD_ResearchandDissert/PhD_Draft/Country-CGE/MAR_adm1.shp")
Sah <- readShapeSpatial("F:/Purdue University/RA_Position/PhD_ResearchandDissert/PhD_Draft/Country-CGE/ESH_adm1.shp")
# Ploting the maps (raw)
png("Morocco.png")
Morocco <- readShapePoly("F:/Purdue University/RA_Position/PhD_ResearchandDissert/PhD_Draft/Country-CGE/MAR_adm1.shp")
plot(Morocco)
dev.off()
png("WesternSahara.png")
WesternSahara <- readShapePoly("F:/Purdue University/RA_Position/PhD_ResearchandDissert/PhD_Draft/Country-CGE/ESH_adm1.shp")
plot(WesternSahara)
dev.off()
After looking into suggestions from #AriBFriedman and #PaulHiemstra and subsequently figuring out how to merge .shp files, I have managed to produce the following map using the following code and data (For .shp data, cf. links above)
code:
# Merging Mor and Sah .shp files into one .shp file
MoroccoData <- rbind(Mor#data,Sah#data) # First, 'stack' the attribute list rows using rbind()
MoroccoPolys <- c(Mor#polygons,Sah#polygons) # Next, combine the two polygon lists into a single list using c()
summary(MoroccoData)
summary(MoroccoPolys)
offset <- length(MoroccoPolys) # Next, generate a new polygon ID for the new SpatialPolygonDataFrame object
browser()
for (i in 1: offset)
{
sNew = as.character(i)
MoroccoPolys[[i]]#ID = sNew
}
ID <- c(as.character(1:length(MoroccoPolys))) # Create an identical ID field and append it to the merged Data component
MoroccoDataWithID <- cbind(ID,MoroccoData)
MoroccoPolysSP <- SpatialPolygons(MoroccoPolys,proj4string=CRS(proj4string(Sah))) # Promote the merged list to a SpatialPolygons data object
Morocco <- SpatialPolygonsDataFrame(MoroccoPolysSP,data = MoroccoDataWithID,match.ID = FALSE) # Combine the merged Data and Polygon components into a new SpatialPolygonsDataFrame.
Morocco#data$id <- rownames(Morocco#data)
Morocco.fort <- fortify(Morocco, region='id')
Morocco.fort <- Morocco.fort[order(Morocco.fort$order), ]
MoroccoMap <- ggplot(data=Morocco.fort, aes(long, lat, group=group)) +
geom_polygon(colour='black',fill='white') +
theme_bw()
Results:
New Question:
1- How to eliminate the boundaries data that cuts though the map in half?
2- How to combine different regions within a .shp file?
Thanks you all.
P.S: the community in stackoverflow.com is wonderful and very helpful, and especially toward beginners like :) Just thought of emphasizing it.
Once you have loaded your shapefiles into Spatial{Lines/Polygons}DataFrames (classes from the sp-package), you can use the fortify generic function to transform them to flat data.frame format. The specific functions for the fortify generic are included in the ggplot2 package, so you'll need to load that first. A code example:
library(ggplot2)
polygon_dataframe = fortify(polygon_spdf)
where polygon_spdf is a SpatialPolygonsDataFrame. A similar approach works for SpatialLinesDataFrame's.
The difference between my solution and that of #AriBFriedman is that mine includes the x and y coordinates of the polygons/lines, in addition to the data associated to those polgons/lines. I really like visualising my spatial data with the ggplot2 package.
Once you have your data in a normal data.frame you can simply use write.csv to generate a csv file on disk.
I think you mean you want the associated data.frame from each?
If so, it can be accessed with the # slot access function. The slot is called data:
write.csv( WesternSahara#data, file="/home/wherever/myWesternSahara.csv")
Then when you read it back in with read.csv, you can try assigning:
myEdits <- read.csv("/home/wherever/myWesternSahara_modified.csv")
WesternSahara#data <- myEdits
You may need to do some massaging of row names and so forth to get it to accept the new data.frame as valid. I'd probably try to merge the existing data.frame with a csv you read in in R, rather than making edits destructively....

How to get coordinates of a path from svg file into R

May be it is a silly question but I don't have a lot of experience doing this. I need to get the coordinates from a polygon to create a contour in R. It is a complex polygon of about 1000 points so to input the coordinates manually is crazy. Also I need to extract the xy position of some objects inside the contour.
I tried to use Illustrator and Inkscape to create an svg file that contains all the information. It looks like a good option considering that the svg file contains all the information. Is there a way to extract the coordinates from the path or polygon nods? or there is any other simpler way to do this process?
I will really appreciate any help because I have to do it for around 30 images.
Cheers
You can use the XML package to extract the coordinates.
# Sample data
library(RCurl)
url <- "http://upload.wikimedia.org/wikibooks/en/a/a8/XML_example_polygon.svg"
svg <- getURL(url)
# Parse the file
library(XML)
doc <- htmlParse(svg)
# Extract the coordinates, as strings
p <- xpathSApply(doc, "//polygon", xmlGetAttr, "points")
# Convert them to numbers
p <- lapply( strsplit(p, " "), function(u)
matrix(as.numeric(unlist(strsplit(u, ","))),ncol=2,byrow=TRUE) )
p
However, this ignores any transformation to be applied to the polygon.

Resources