incorrect plotting state borders - r

I am intending to plot a county level map with 5 colors depending on a value of an attribute. I did that with no problems. Now, I want to add the state borders and the end result is not good. The border lines are too straight and the limits of the states are not well plotted. They do not follow the actual limits of the states.
Here is the code I am using:
# Pick the colors for the categorical values
colors = c("#CC0000", "#FF9999", "#E0E0E0", "#99FF99", "#00CC00")
#Creates a new variable with the categories.
data$colorBuckets <- as.numeric(cut(data$Slope, c(-0.30, -0.20, -0.10, 0.10,
0.20, 0.30)))
# Put a 3 (equivalent to slope 0) when there is NA's
data$colorBuckets[is.na(data$colorBuckets)] <- 3
# Matches the values of FIPS with the color categories
colorsmatched <- data$colorBuckets
library(mapproj)
# Map colored counties according the categories
map("county", col = colors[colorsmatched], fill = TRUE, resolution = 0,
lty = 0, projection = "polyconic")
# Add border around each county
map("county", col = "gray", fill = FALSE, add = TRUE, lty = 1, lwd = 0.2,
projection = "polyconic")
# Add border to each state (THIS IS THE PROBLEMATIC STEP)
map("state", col = "black", fill = FALSE, add = TRUE, lty = 1, lwd = 0.4,
projection = "polyconic")
Any idea why this may be happening?

Related

Plotting map points returning an unkwown output

Was constructing a series of plots for extracting bathymetric data and an rare output comes out when trying to generate the last b/w plot with my data. Here are my data coord (12sites_lat_long2.txt).
SITE,LAT,LONG
TAD,48.133119,-69.705842
IV,48.034772,-69.340821
LUD,49.161609,-68.173798
SAM,49.130887,-66.500031
NOR,50.163282,-66.467896
PUR,50.151276,-66.325630
NEW,48.263541,-64.735703
PAS,48.017946,-65.265587
BON,48.041124,-65.491133
COR,47.496607,-61.723938
ROO,47.806514,-61.232300
CAO,48.5058323,-64.2231551
And here my code were i downloaded the bathymetric set and ploted
library(marmap)
library(dplyr)
library(SoDA)
library(ade4)
library(adespatial)
library(ggmap)
library(ggplot2)
library(reshape2)
library(dartR)
library(BiocManager)
library(devtools)
library(plotly)
library(directlabels)
sites <- read.table("12sites_lat_long2.txt", header=TRUE,dec=".",sep=",")
#Order the site object and check the sites positions
sites <- sites %>% dplyr::arrange(SITE)
summary(sites)
#Keep only latitude and longitude info
sites_depth <- dplyr::select(sites,LONG,LAT)
#Get the bathimetric Data and build a matrix
#in this case, we get the data from NOAA using the marmap package
bathydata <- marmap::getNOAA.bathy(lon1= -70.2966,
lon2= -60.9692,
lat1= 51.2392,
lat2= 46.6170,
resolution = 1)
#Summarizing the data
summary(bathydata)
#Next, we extract the bathimetric data
#We plot map according to different levels of depth seting colors for each level
blues <- colorRampPalette(c("lightblue", "cadetblue2", "cadetblue1", "white"))
blues <- c("lightsteelblue4", "lightsteelblue3","lightsteelblue2", "lightsteelblue1")
greys <- c(grey(0.6), grey(0.93), grey(0.99))
#And Plot a map with the colors created
plot(bathydata, image = TRUE, land = TRUE, n=1,
bpal = list(c(0, max(bathydata), greys),
c(min(bathydata), 0, blues)))
#add the sampling points and text to the plot
points(sites$LON, sites$LAT, pch = 21, col = "black",
bg = "yellow", cex = 1.3)
text(sites$LON, sites$LAT,sites$SITE, pos = 2)
# plot a map without color
pdf("Marmap_saccharina.pdf")
plot(bathydata, lwd = c(0.3, 1), lty = c(1, 1),
deep = c(-4500, 0), shallow = c(-50, 0),
step = c(500, 0),
col = c("grey", "black"), drawlabels = c(FALSE, FALSE))
scaleBathy(bathydata, deg = 3, x = "bottomleft", inset = 5)
points(sites$LON, sites$LAT, pch = 21, col = "black", bg = "grey", cex = 1)
text(sites$LON, sites$LAT,sites$SITE, pos = 1,cex = 0.5)
dev.off()
The output that I get instead of the map is just
RStudioGD
2
I was expecting a map similar to this one
example
I have searched but have no clue what this output is refering to and were is the error

How to add centroids to an RDA plot

I'd like to replace the arrows on this RDA plot with centroids, something like what's pictured here.
This is the code I currently have which provides me arrows (I guess by default). I have shared our RDA code and I think this is where we might be able to change it from arrows to centroid:
# add arrows for effects of the expanatory variables
arrows(0,0, # start them from (0,0)
sc_bp[,1], sc_bp[,2], # end them at the score value
col = "red",
lwd = 1,
length = .1)
(but I share the entire code chunk (below), just in case.
Please note that my data is on fish community (species) and substrate types at 36 sites, I'd like to replace the arrows for substrates with centroids within my RDA.
##Now, the RDA
Y.mat<-Belt_2021_fish_transformed_forPCA #fish community
str(Y.mat)
X.mat<-Reefcheck_2021_forPCA #substrate
str(X.mat)
###Community data has already been transformed with hellinger
##Now, try the RDA
fish_substrate_rda<-rda(Y.mat,X.mat)
```
##Plot
## extract % explained by the first 2 axes
perc_b <- round(100*(summary(fish_substrate_rda)$cont$importance[2, 1:2]), 2)
## extract scores - these are coordinates in the RDA space
sc_si <- scores(fish_substrate_rda, display="sites", choices=c(1,2), scaling=1)
sc_sp <- scores(fish_substrate_rda, display="species", choices=c(1,2), scaling=1)
sc_sp <- sc_sp[c(2,7,8),]
sc_bp <- scores(fish_substrate_rda, display="bp", choices=c(1,2), scaling=1)
sc_bp <- sc_bp[c(2,5,6),]
# Set up a blank plot with scaling, axes, and labels
plot(fish_substrate_rda,
scaling = 1, # set scaling type
type = "none", # this excludes the plotting of any points from the results
frame = TRUE,
# set axis limits
ylim = c(-1.5,0.7),
xlim = c(-1.5,1.2),
# label the plot (title, and axes)
main = "Triplot RDA - scaling 1",
xlab = paste0("RDA1 (", perc_b[1], "%)"),
ylab = paste0("RDA2 (", perc_b[2], "%)")
)
# add points for site scores
points(sc_si,
pch = 21, # set shape (here, circle with a fill colour)
col = "black", # outline colour
bg = "steelblue", # fill colour
cex = 0.7) # size
# add points for species scores
points(sc_sp,
pch = 22, # set shape (here, square with a fill colour)
col = "black",
bg = "#f2bd33",
cex = 0.7)
# add text labels for species abbreviations
text(sc_sp + c(-0.09, -0.09), # adjust text coordinates to avoid overlap with points
labels = rownames(sc_sp),
col = "grey40",
font = 2, # bold
cex = 0.6)
# add arrows for effects of the expanatory variables
arrows(0,0, # start them from (0,0)
sc_bp[,1], sc_bp[,2], # end them at the score value
col = "red",
lwd = 1,
length = .1)
# add text labels for arrows
text(x = sc_bp[,1] -0.01, # adjust text coordinate to avoid overlap with arrow tip
y = sc_bp[,2] - 0.09,
labels = rownames(sc_bp),
col = "red",
cex = .7,
font = 1)
```
I have not found anything online that might help me to accomplish this.

contourplot color and labels options in Lattice for R

I am quite new to Lattice and I am stuck with some possibly basic coding. I am using shapefiles and geoTIFFS to produce maps of animals distribution and in particular I have:
1 x point shapefile
2 x geoTIFF
1 x polygon shapefile
I am overlapping a levelplot of one of the geoTIFF (UD generated with adehabitatHR) with a contourplot of the same geoTIFF at specific intervals (percentile values), a contourplot of the second geoTIFF (depth raster from ETOPO2) for three specific values (-200, -1000 and -2000), the point shapefile (animal locations) and the polygon shapefile (land). All works fine but I need to change the font size of contour plot labels, their length (i.e. from 0.12315 to 0.123) and positioning for all the contourplots. For the depth contourplot I would like to change the style of each line in something like "continous line", "dashed line" and "point line", and for the contourplot of the UD I would like to change the color of each line using a yellow to red palette.
As far as I understand, I should use panel functions to implement these changes (e.g. Controlling z labels in contourplot) but i am not quite sure how to do it. Part of my code to generate the "plot":
aa <-
quantile(
UD_raster,
probs = c(0.25, 0.75),
type = 8,
names = TRUE
)
my.at <- c(aa[1], aa[2])
depth<-c(-100, -200, -2000)
levelplot(
UD_raster,
xlab = "",
ylab = "",
margin = FALSE,
contour = FALSE,
col.regions = viridis(100),
main = "A",
maxpixels = 2e5
) + layer(sp.polygons(Land, fill = "grey40", col = NA)) + layer(sp.points(locations, pts = 2, col = "red")) + contourplot(
UD_raster,
at = my.at,
labels = TRUE,
margin = FALSE
) + contourplot(
ETOPO2,
at = depth,
labels = TRUE,
margin = FALSE
)
A simplified image, with no UD layer and no point shapefile can be found here and as you can see it is pretty messy. Thanks for your help.
So far for the ETOPO2 countourplot I have solved by eliminating the labels and adding the argument lty to style the line. Because I can't figure out how to use lty with different values for each single line in my contour, I have replicated the contourplot function three times on the same surface, one for each contour I am interested into (this was easy because I only need three contours).
For the position, font and font size of the labels of the remaining contourplot I have used
labels = list(cex = 0.8, "verdana"),
label.style = "flat"
To "shorten" the length of the labels I have used the function round where I specify to which decimal digit to round number.
So now my new code looks like:
aa <-
quantile(
UD_raster,
probs = c(0.25, 0.75),
type = 8,
names = TRUE
)
my.at <- c(aa[1], aa[2])
my.at <- round(my.at, 3)
levelplot(
UD_raster,
xlab = "",
ylab = "",
margin = FALSE,
contour = FALSE,
col.regions = viridis(100),
main = "A",
maxpixels = 2e5
) + layer(sp.polygons(Land, fill = "grey40", col = NA)) + layer(sp.points(positions, pts = 2, col = "red")) + contourplot(
UD_raster,
at = my.at,
labels = list(cex = 0.8, "verdana"),
label.style = "flat",
margin = FALSE
) + contourplot(
ETOPO2,
at = -200,
labels = FALSE,
margin = FALSE,
lty = 1,
pretty = TRUE
) + contourplot(
ETOPO2,
at = -1000,
labels = FALSE,
margin = FALSE,
lty = 2,
pretty = TRUE
) + contourplot(
ETOPO2,
at = -2000,
labels = FALSE,
margin = FALSE,
lty = 3,
pretty = TRUE
)
As one could expect, it takes a bit longer to produce the plot. Still no idea on how to change the colors of the UD contourplot.

Manipulating "missing" label in legend: tmap

I want to manipulate the "Missing" label in my legend.
I'm using the tmap function in R. I want to change it to read "Missing or not eligible to gentrify"
I have tried using the tm_text function and considered how I would change the label in the underlying data, but haven't found a solution. Also, note the code uses a mapping function.
########################
# categorical mapping function
########################
cat.maps.wide.function <- function(data, varname, ltitle, colorplaette){
tm_shape(data, unit = "mi") +
tm_polygons(col = varname , # add variable(s)
style = "cat", # set break pattern to object LQ.cuts
palette = colorplaette, # set color fill to blue refreshing
border.col = "grey40", # color the borders white
border.alpha = 0.5, # set border transparency
title = ltitle, # title for legend
colorNA = "white") + # color of missing data
tm_style("bw") +
tm_layout(panel.label.bg.color ="NA",
frame = FALSE,
bg.color = "transparent") + # panel label color
tm_legend(legend.title.fontface = 2, # legend bold
legend.title.size = 0.75,
legend.text.size = 0.65,
legend.bg.alpha = 0,
legend.width = 5) +
tm_scale_bar(color.dark = "gray60", # Customize scale bar and north arrow
position = c(0.6, 0.05)) + # set position of the scale bar
tm_compass(type = "4star",
size = 2.5, # set size of the compass
fontsize = 0.5, # set font size of the compass
color.dark = "gray60", # color the compass
text.color = "gray60", # color the text of the compass
position = c(0.5, 0.05)) + # set position of the compass
# add border names
tm_shape(boro.boundaries) +
tm_borders(alpha = .5) +
tm_text("boro",
size = 0.75,
remove.overlap = TRUE,
auto.placement=FALSE,
xmod= "x", ymod= "y")
}
########################
# change in residential housing price
########################
# object for 2016 variable
mt1pva5.2016 <- cat.maps.wide.function(
data = data.map.tract.wide,
varname = "chgpcmt1pva5_overlap2016",
colorplaette = mt1pva5.overlap.colors,
ltitle = "Change in residential housing price for eligible tracts ")
mt1pva5.2016
Thanks for sharing the data. Apparently, you can use labels in tm_polygons but not to change the NA values. For that, you also will need textNA:
tm_polygons(col = varname , # add variable(s)
style = "cat", # set break pattern to object LQ.cuts
palette = colorplaette, # set color fill to blue refreshing
border.col = "grey40", # color the borders white
border.alpha = 0.5, # set border transparency
title = ltitle, # title for legend
colorNA = "white", # color of missing data
textNA = "Missing or not eligible to gentrify",
labels = c("Decrease in residential housing price",
"Increase in residential housing price")) +
...
the tm_layout() functin has the labels argument which lets you maniputale the label of the legend passing a character vector. In yout tm_layout add something like:
tm_layout(labels = c("Decrease in residential housing price",
"Increase in residential housing price",
"Missing or not eligible to gentrify")

Reduce whitespace in corrplot in R

I have a 1 row 2 column plot which I need to insert into a report. When I insert the plot I notice there's a large white area around both correlation plots. Is there an argument in the corrplot function to reduce this? I've read here about using knitr hook functions to crop pdfs but that a bridge too far for my coding capabilities. I've messed around with the par() arguments such as omi and mai but when I export the image to TIFF I still get a huge white space area.
My code so far looks as follows, please note this is hacked together from various sources and dputs to both correlation matrices can be found here and here:
col <- colorRampPalette(c("#BB4444", "#EE9988", "#FFFFFF", "#77AADD", "#4477AA"))
par(mfrow=c(1,2),omi=c(0,0,0,0),mai=c(0.1,0.1,0.1,0.1))
corrplot(LX0088U21A1_24hrCor, method = "color", col = col(200),
type = "upper", order = "original", number.cex = 0.85,
addCoef.col = "black", # Add coefficient of correlation
tl.col = "black", tl.srt = 90,
number.digits = 1,
# Text label color and rotation
# hide correlation coefficient on the principal diagonal
diag = FALSE,
#title = "Intraday Correlation LX0088U21A1",
mar=c(0,0,1,0))
legend(0.5,5,ncol = 1, cex = 1.5,legend = "(a)", box.lwd = 0, box.col = "white")
corrplot(LX0088U09A3_24hrCor, method = "color", col = col(200),
type = "upper", order = "original", number.cex = 0.75,
addCoef.col = "black", # Add coefficient of correlation
tl.col = "black", tl.srt = 90,
number.digits = 1,
# Text label color and rotation
# hide correlation coefficient on the principal diagonal
diag = FALSE,
#title = "Intraday Correlation LX0088U09A3",
mar=c(0,0,1,0))
legend(0.5,5,ncol = 1, cex = 1.5,legend = "(b)", box.lwd = 0, box.col = "white")
Any help is greatly appreciated.

Resources