R shiny image resize - r

height <- dim(img)[1]
width <- dim(img)[2]
screen_resolution <<- (width/height)
points_df <<- data.frame(x = as.numeric(xy_new$x), y = as.numeric(xy_new$y))
coordinates <- c(as.numeric(xy_new$x),as.numeric(xy_new$y))
point <- rbind(point, coordinates)
plot(coord$x, coord$y, xlim=c(0, dim(img)[2]), ylim=c(dim(img)[1],0), xlab="X", ylab="Y", xaxt = "n")
axis(1, at = seq(0, dim(img)[2], by = 50))
axis(2, at = seq(dim(img)[1],0, by = -50))
rasterImage(img, 0, dim(img)[2], dim(img)[1], 0)
First of all, thanks in advance to everyone trying to help.
In this code block, the image placed on the plot is compressed from the top. Is there a way to plot and dynamically align it without breaking the resolution of the image?

Related

Reduce space between names.arg and axis (box) in barplot

I created a simple barplot surrounded by a box. Is there any way to move my names closer to the box (space marked in blue)?
MWE:
set.seed(1)
count <- runif(n = 3, min = 0, max = 10)
names <- letters[seq(from = 1, to = 3)]
barplot(height = count,
names.arg = names,
horiz = TRUE,
las = 1)
box()
Here are two ways to do this. You can use rect instead of box to move the box boundary to the left:
barplot(height=count, names.arg=names, horiz=TRUE, las=1)
bounds <- par("usr")
rect(bounds[1]-.1, bounds[3], bounds[2], bounds[4], xpd=NA)
Or you can add the y-axis separately which lets you control where the labels are plotted:
x <- barplot(height=count, horiz=TRUE, las=1)
box()
axis(2, x, names, las=1, tick=FALSE, mgp=c(2, .35, 0))
Adjust the middle value in mgp to position the labels (see ?par)

Can't limit boundaries of a plotted shapefile properly

I can't really set the boundaries of my plotted shapefile. I'm plotting the shapefile first to get nice x- and y- labels in degrees first, plotting the data afterwards. In the end, I'm plotting my shapefile over the data again. ylim is changeable, but xlim seems to be solely dependend on ylim changes, because I cant vary xlim itself. It only varies, when I change ylim without changing xlim, like as it is an aspect ratio issue.
I want to limit the x-axis between 8.5 and 11.5 degrees.
A link to the shapefile and raster in question: https://www.dropbox.com/sh/l42mty01mwtm8qc/AADqjNbGkmNwx3o9aFceGrkya?dl=0
My code:
library(rgeos)
library(rgdal)
library(raster)
Sys.setlocale(category = "LC_ALL", locale = "C") # In the case German Umlauts are a problem while reading the shapefile
map <- readOGR("C:\\Path\\NATRAUM_MR_utm32.shp")
# Exclude unnecessary regions
map <- subset(map, NATREGNR != 3)
map <- subset(map, NATREGNR != 4)
map <- subset(map, NATREGNR != 9)
map_wgs84 <- spTransform(map, crs(raster.percent.change.rcp85.1971_2005.2071_2100))
# Pixelplot
par(mar = c(3, 3, 2, 1)) # For saving pictures through a device like pdf
m <- plot(map_wgs84, axes=TRUE, xlim = c(8.5, 11.5), ylim=c(51.35, 53.15), cex = .5,
bty = "n")
# Colortable for legend
colTab <- c("#0033CC", "#3366FF", "#6699FF","#99FFFF", "#FFCC99","#FF9933", "#FF4D00","#660000")
N <- length(colTab)
breaks <- seq(-2, 2, length.out= N+1 )
plot(raster.percent.change.rcp85.1971_2005.2071_2100, col = colTab, breaks = breaks,
axis.args = list(cex.axis = 1, at = breaks, labels = breaks, mgp = c(1, 0, 0), tck = 0.1),
legend.args = list(text='Change [%]', side=4, font=2, line=1.75, cex=0.7),
add = TRUE
)
plot(map_wgs84, add = TRUE) # Plotting shapefile over data
You need to resize your plotting window. You can use par(fin=c(x,y)), or png() to set a ratio that works, and fix that in code.
This is because for maps, the correct aspect (ratio of vertical and horizontal extent) is enforced. For planar data the aspect is 1. For angular data (longitude/latitude) it varies by latitude.
With some data.
library(raster)
p <- shapefile(system.file("external/lux.shp", package="raster"))
Compare:
par(fin=c(6,6))
plot(p, axes=T, xlim=c(6,6.2), ylim=c(49.6, 49.8))
par(fin=c(4, 6))
plot(p, axes=T, xlim=c(6,6.2), ylim=c(49.6, 49.8))

R plot,why is introducing of axis limits creating havoc?

My code
library(Hmisc)
r1 <- read.table("mt7.1r1.rp", header = FALSE)
r2 <- read.table("mt7.1r2.rp", header = FALSE)
r3 <- read.table("mt7.2r1.rp", header = FALSE)
r4 <- read.table("mt7.2r2.rp", header = FALSE)
p1=r1[1]
per1=log10(p1)
p2=r2[1]
per2=log10(p2)
p3=r3[1]
per3=log10(p3)
p4=r4[1]
per4=log10(p4)
m1=nrow(per1)
m2=nrow(per2)
m3=nrow(per3)
m4=nrow(per4)
xmin <- floor( min(per1,per2,per3,per4))
xmax <- ceiling( max(per1,per2,per3,per4))
lxmax=10^(xmax)
lxmin=10^(xmin)
rhoaxy = r2[3]
phaxy = r2[5]
rhoayx = r3[3]
phayx = r3[5]
rhoaxx = r1[3]
phaxx = r1[5]
rhoayy = r4[3]
phayy = r4[5]
per2=unname(per2)
per2=unlist(per2)
per3=unname(per3)
per3=unlist(per3)
rhoaxy=unname(rhoaxy)
rhoaxy=unlist(rhoaxy)
rhoaxy=log10(rhoaxy)
rhoayx=unname(rhoayx)
rhoayx=unlist(rhoayx)
rhoayx=log10(rhoayx)
ymin1=floor(min(rhoaxy)-1)
ymax1=ceiling(max(rhoaxy)+1)
ymin2=floor(min(rhoayx)-1)
ymax2=ceiling(max(rhoayx)+1)
ymin=min(ymin1,ymin2)
ymax=max(ymax1,ymax2)
png("withlim.png")
plot(per2,rhoaxy, col='red', xlab='Per (s)', ylab = 'Rho-xy/yx',ylim=c(ymin, ymax))
par(new=TRUE)
plot(per3,rhoayx, col='green', xaxt='n', xlab= NA, yaxt = 'n', ylab = NA)
dev.off()
The image I got
If I delete ylim
My question is,why are the axis limits changing the image content?The values from the second image correspond to proper data values.The first image is with values that do not represent rhoaxy and rhoayx.
It is difficult to test without the data, but my guess is that, on the second plot, the Y axis is not the same, although the Y axis is not plot.
So you've got the superposition of 2 plot, with a different Y axis.
If you want the same ylim on both plot, add ylim=c(ymin, ymax) on the second plot also.
If it does not work, please provide data example, so we can test.

Single colorkey for raster and points Levelplot R

Using the sample data below, how can I generate rasters and spatial points plot with the same colorkey as in the "manually" joined plot shown below?
library(rasterVis)
library(raster)
library(colorRamps)
col=colorRampPalette(matlab.like2(255))
s <- stack(replicate(2, raster(matrix(runif(100), 10))))
xy <- data.frame(coordinates(sampleRandom(s, 10, sp=TRUE)),
z1=runif(10), z2=runif(10))
levelplot(s, margin=FALSE, at=seq(0, 1, 0.05),col.regions=col)
x=xy$x;y=xy$y;z=xy$z1
levelplot(z ~ x + y,contour=F, panel = panel.levelplot.points,
margin=FALSE,col.regions=col,
par.settings=list(axis.line=list(lwd=3), strip.border=list(lwd=3)),
cex=1.4, scales=list(x=list(cex=1.7),y=list(cex=1.7)),xlab=list(label="Longitude",cex=2),
ylab=list(label="Latitude",cex=2))
Thanks to #fdestch I was able to generate the following plot using:
latticeCombineGrid(mget(rep("pp", 24)), layout = c(3, 8))
following my comments on printing multiple plots with the same colorkey.
An issue that remains to be clarified:
1) How can one decide on the order of panels? That is, which row & column to place a particular plot just as in levelplot using index.cond.
First of all, you should probably make sure that the breaks in the points plot are identical with those defined in the first levelplot.
## raster plot with colorkey disabled
pr <- levelplot(s, margin = FALSE, at = seq(0, 1, 0.05), col.regions = col,
colorkey = FALSE, xlab = list("Longitude", col = "transparent"))
## points plot
pp <- levelplot(z ~ x + y, panel = panel.levelplot.points, cex = 1.4,
contour = FALSE, margin = FALSE, col.regions = col,
colorkey = list(at = seq(0, 1, .05), width = .6, height = .6),
xlab = "Longitude", ylab = "Latitude")
Please note the definition of a transparent xlab when creating the raster plot. This little workaround comes in quite handy when using downViewport later on to ensure that the actual plot boundaries of pr and pp overlap (feel free to run grid.rect() right after print(pr, newpage = FALSE) to see what I mean).
The actual plot arrangement can then easily be achieved by using viewports from the grid package.
library(grid)
library(lattice)
## initialize new grid device
grid.newpage()
## add raster plot
vp1 <- viewport(x = 0, y = 0, width = .5, height = 1,
just = c("left", "bottom"))
pushViewport(vp1)
print(pr, newpage = FALSE)
## add points plot
downViewport(trellis.vpname("page"))
vp2 <- viewport(x = 1, y = 0, width = .75, height = 1,
just = c("left", "bottom"))
pushViewport(vp2)
print(pp, newpage = FALSE)
Here is my solution using latticeExtra::c.trellis:
library(raster)
library(rasterVis)
s <- stack(replicate(2, raster(matrix(runif(100), 10))))
xy <- data.frame(coordinates(sampleRandom(s, 10, sp=TRUE)),
z1=runif(10), z2=runif(10))
## Define theme and breaks
myTheme <- BTCTheme()
my.at <- seq(0, 1, 0.05)
Plot the Raster* object, using rasterVis::levelplot:
p1 <- levelplot(s, margin=FALSE,
at = my.at,
par.settings = myTheme)
Plot the points, using lattice::levelplot:
p2 <- levelplot(z1 ~ x + y, data = xy,
at = my.at,
panel = panel.levelplot.points,
par.settings = myTheme)
Join them with latticeExtra::c.trellis:
p3 <- c(p1, p2, layout = c(3, 1))
Unfortunately, c.trellis does not assign the strip labels correctly, so you have to define them directly:
update(p3,
strip = strip.custom(factor.levels = c(names(s), "Points")))

Plot margin of pdf plot device: y-axis label falling outside graphics window

I tried simply plotting some data in R with the y-axis label horizontal and left of the y-axis tick labels. I thought the code below would work:
set.seed(1)
n.obs <- 390
vol.min <- .20/sqrt(252 * 390)
eps <- rnorm(n = n.obs, sd = vol.min)
mar.default <- c(5,4,4,2) + 0.1
par(mar = mar.default + c(0, 4, 0, 0)) # add space to LHS of plot
pdf("~/myplot.pdf", width=5.05, height=3.8)
plot(eps, main = "Hello World!", las=1, ylab="") # suppress the y-axis label
mtext(text="eps", side=2, line=4, las=1) # add horiz y-axis label
# 4 lines into the margin
Instead, as you may see, the y-axis label almost fell completely outside of the graphics window. This phenomenon still exists no matter how much I expand the LHS margin.
Q: What am I doing wrong? Is there something I need to do with the oma parameter? What do I need to do to plot things the way I'm intending? I'm a little overwhelmed by all of this!
This is a classic one, maybe should be a FAQ. You have to set the par settings after the call to pdf, which creates the plotting device. Otherwise you're modifying the settings on the default device:
set.seed(1)
n.obs <- 390
vol.min <- .20/sqrt(252 * 390)
eps <- rnorm(n = n.obs, sd = vol.min)
# add space to LHS of plot
pdf("~/myplot.pdf", width=5.05, height=3.8)
mar.default <- c(5,4,4,2) + 0.1
par(mar = mar.default + c(0, 4, 0, 0))
plot(eps, main = "Hello World!", las=1, ylab="") # suppress the y-axis label
mtext(text="eps", side=2, line=4, las=1)
dev.off()

Resources