integer(0) when plotting a shapefile and points - r

I am plotting points over a shapefile and R keeps printing "integer(0)" after it completes the command. It plots fine, which can be seen in this reproducible example (with jarring colors because FUN=had ;-) )
### get Germany as shp
Germany.shp<-getData("GADM", country="DEU",level=1,download=T,path=getwd())
par(mfrow=c(1,2))
plot(Germany.shp, col="magenta", main="plots normally")
### make up some spatial points (yes, the proper cities in Germany)
points.df<-data.frame(name=c("Berlin","Frankfurt","Rostock"),
lat=c(52.5243700,50.1155200,54.0887000), long=c(13.4105300,8.6841700,12.1404900))
coordinates(points.df)=~long+lat ### converts df to spatial df
crs(points.df)<-CRS("+init=epsg:4326") ### defines CRS
points.df<-spTransform(points.df,crs(Germany.shp)) ### project to same CRS as Germany.shp
### plot
plot(Germany.shp, col="magenta", sub="is 0 actually in integer? just asking",main="integer 0",)+
points(points.df,col="blue", pch=16,cex=2.2)
### !!! ### CONSOLE shows integer(0), plots perfectly well though ### !!! ###
I was really worried initially, since I am plotting 35000 points in my actual dataset. So I made up this example to cross-check and the cities are in the right place. However I am using a markdown and have 10-15 plots like this and thus have to manually delete the "integer(0)" console output manually. annoying ;)

There seem to be several solutions.
easiest is to add your plot() to an object:
x<-plot()
Others have suggested wrapping it in invisible() or adjusting markdown settings to results="hide"
But making your plots into objects (imo) allows most flexibility and the opportunity to arrange the objects later so that you can plot them agian!

Related

Can I "turn off" arrows where the value is 0 in vectorplot? (no currents on land)

I am trying to make a map of Guam's current field using vectorplot in the rasterVis package. When I read in my original data where the currents on "land" were NA, I got errors so I am instead using a file where velocity on land is 0. But this means I get current vector arrows on land in my plot.
Is it possible to "tell" the plot not to plot vectors if the value =0? I am very new to rasterVis and grateful for any advice!
NetCDF file for current data can be found here: https://drive.google.com/drive/folders/12h9jN0rI6An8kF56ugNhODtVa40Z8vV0?usp=sharing[![enter image description here]1]1
ncfile_org <- 'guaROMS_2021Apr25May21_nan.nc'
ucomp <- brick(ncfile_org, varname='u')
vcomp <- brick(ncfile_org, varname='v')
desired date to plot
d=181
ucomp1 <- ucomp[[d]]
vcomp1 <- vcomp[[d]]
ucomp1[is.na(ucomp1[])]=0
vcomp1[is.na(vcomp1[])]=0
uv=stack(ucomp1,vcomp1)
Plot Guam with current vectors. Note, I have changed the viridis palette so that "land" (velocity=0) is white.
vectorplot(uv,isField="dXY",region=TRUE,
par.setting=viridisTheme(region=c("#FFFFFFFF",viridis(10))))
Thank you so much for your help.

Represent a colored polygon in ggplot2

I am using the statspat package because I am working on spatial patterns.
I would like to do in ggplot and with colors instead of numbers (because it is not too readable),
the following graph, produced with the plot.quadratest function: Polygone
The numbers that interest me for the intensity of the colors are those at the bottom of each box.
The test object contains the following data:
Test object
I have looked at the help of the function, as well as the code of the function but I still cannot manage it.
Ideally I would like my final figure to look like this (maybe not with the same colors haha):
Final object
Thanks in advance for your help.
Please provide a reproducible example in the future.
The package reprex may be very helpful.
To use ggplot2 for this my best bet would be to convert
spatstat objects to sf and do the plotting that way,
but it may take some time. If you are willing to use base
graphics and spatstat you could do something like:
library(spatstat)
# Data (using a built-in dataset):
X <- unmark(chorley)
plot(X, main = "")
# Test:
test <- quadrat.test(X, nx = 4)
# Default plot:
plot(test, main = "")
# Extract the the `quadratcount` object (regions with observed counts):
counts <- attr(test, "quadratcount")
# Convert to `tess` (raw regions with no numbers)
regions <- as.tess(counts)
# Add residuals as marks to the tessellation:
marks(regions) <- test$residuals
# Plot regions with marks as colors:
plot(regions, do.col = TRUE, main = "")

R Highlighting some of the boundaries (or borders) of the region in a shape file with spplot()

I am working on a shape file and like to highlight some of the boundaries (borders) of the regions (as figure 1):
Figure 1: some but not all of the regions (borders) of the shape file are highlighted
(Source: https://dl.dropboxusercontent.com/u/48721006/highlighted.png)
The highlighting is achieved with ArcMap. I can't figure out how to do the same with R (particularly with the spplot()). Any suggestions on this?
To get the shape file
library(sp)
library(maptools)
con <- url("http://gadm.org/data/rda/ZAF_adm2.RData")
print(load(con))
close(con)
plot(gadm)
Many thanks!
G
What I would do: (1) plot the complete set; (2) take a subset; (3) plot the subset with a different line type. For subsetting shape files, check this question.
plot(gadm)
# check class and structure of the data
class(gadm)
head(gadm#data)
# take a subset based on ID_2
some_polygons = subset(gadm,ID_2>=38840 & ID_2<38850)
plot(some_polygons, add=T, border='cyan', lwd=2)

rCharts Polychart: Adding horizontal or vertical lines to a plot

I'm having some trouble understanding how to customize graphs using the rPlot function in the rCharts Package. Say I have the following code
#Install rCharts if you do not already have it
#This will require devtools, which can be downloaded from CRAN
require(devtools)
install_github('rCharts', 'ramnathv')
#simulate some random normal data
x <- rnorm(100, 50, 5)
y <- rnorm(100, 30, 2)
#store in a data frame for easy retrieval
demoData <- data.frame(x,y)
#generate the rPlot Object
demoChart <- rPlot(y~x, data = demoData, type = 'point')
#return the object // view the plot
demoChart
This will generate a plot and that is nice, but how would I go about adding horizontal lines along the y-axis? For example, if I wanted to plot a green line which represented the average y-value, and then red lines which represented +/- 3 standard deviations from the average? If anybody knows of some documentation and could point me to it then that would be great. However, the only documentation I could find was on the polychart.js (https://github.com/Polychart/polychart2) and I'm not quite sure how to apply this to the rCharts rPlot function in R.
I have done some digging and I feel like the answer is going to have something to do with adding/modifying the layers parameter within the rPlot object.
#look at the slots in this object
demoChart$params$layers
#doing this will return the following output (which will be different for
#everybody because I didn't set a seed). Also, I removed rows 6:100 of the data.
demoChart$params$layers
[[1]]
[[1]]$x
[1] "x"
[[1]]$y
[1] "y"
[[1]]$data
x y
1 49.66518 32.75435
2 42.59585 30.54304
3 53.40338 31.71185
4 58.01907 28.98096
5 55.67123 29.15870
[[1]]$facet
NULL
[[1]]$type
[1] "point"
If I figure this out I will post a solution, but I would appreciate any help/advice in the meantime! I don't have much experience playing with objects in R. I feel like this is supposed to have some similarity to ggplot2 which I also don't have much experience with.
Thanks for any advice!
You can overlay additional graphs onto your rCharts plot using layers. Add values for any additional layers as columns on to your original data.frame. copy_layer lets you use the values from the data.frame in the extra layers.
# Regression Plots using rCharts
require(rCharts)
mtcars$avg <- mean(mtcars$mpg)
mtcars$sdplus <- mtcars$avg + sd(mtcars$mpg)
mtcars$sdneg <- mtcars$avg - sd(mtcars$mpg)
p1 <- rPlot(mpg~wt, data=mtcars, type='point')
p1$layer(y='avg', copy_layer=T, type='line', color=list(const='red'))
p1$layer(y='sdplus', copy_layer=T, type='line', color=list(const='green'))
p1$layer(y='sdneg', copy_layer=T, type='line', color=list(const='green'))
p1
Here are a couple of examples: one from the main rCharts website and the other showing how to overlay a regression line.

Clearing plotted points in R

I am trying to use the animation package to generate an "evolving" plot of points on a map. The map is generated from shapefiles (from the readShapeSpatial/readShapeLines functions).
The problem is when it's plotted in a for loop, the result is additive, whereas the ideal result is to have it evolve.
Are there ways of using par() that I am missing?
My question is: is there a way to clear just the points ploted from the points function
and not clearing the entire figure thus not having to regraph the shapefiles?
in case someone wants to see code:
# plotting underlying map
newyork <- readShapeSpatial('nycpolygon.shp')
routes <- readShapeLines('nyc.shp')
par(bg="grey25")
plot(newyork, lwd=2, col ="lightgray")
plot(routes,add=TRUE,lwd=0.1,col="lightslategrey")
# plotting points and save to GIF
ani.options(interval=.05)
saveGIF({
par(bg="grey25")
# Begin loop
for (i in 13:44){
infile <-paste("Week",i,".csv",sep='')
mydata <-read.csv(file = infile, header = TRUE, sep=",")
plotvar <- Var$Para
nclr <- 4
plotclr <-brewer.pal(nclr,"RdPu")
class<- classIntervals(plotvar,nclr,style = "pretty")
colcode <- findColours(class,plotclr)
points(Var$Lon,Var$Lat,col=colcode)
}
})
If you can accept a residual shadow or halo of ink, you can over-plot with color ="white" or == to your background choices. We cannot access your shape file but you can try it out by adding this line:
points(Var$Lon, Var$Lat, col="grey25")
It may leave gaps in other previously plotted figures or boundaries, because it's definitely not object-oriented. The lattice and ggplot2 graphics models are more object oriented, so if you want to post a reproducible example, that might be an alternate path to "moving" forward. I seem to remember that the rgl package has animation options in its repetoire.

Resources