I would like to highlight certain points (without the adjacent lines) in an ecdf plot. The problem is, that either
a) using col, the lines left of these points get labelled as well:
b) using bg has absolutely no effect even if specifying a pch that normally uses bg:
Where is my mistake? Is there an easy way to do that (other then to extract the ecdf function data and create the plot by hand)? I prefer plain plotting over ggplot etc. Thanks in advance!
set.seed(seed=123)
dta=rnorm(20)
plot(1:2, pch=c(19, 25), col="blue", bg="red", cex=5, lwd=4)
# works perfectly (note: pch=19 only has col, no bg, whereas others (e.g. 25) have col (border) and bg (fill))
# a)
plot(ecdf(dta), pch=19, col=c("gray","red"))
# colored symbols AND lines, but I only want to color the symbols (see 1st figure above)
# b)
plot(ecdf(dta), pch=25, col="gray",bg="red")
# specifying bg does not work from plot.ecdf (see 2nd fig. above)
Would this work for you?
set.seed(seed=123)
dta=rnorm(20)
##
plot(ecdf(dta), pch=19,
col="gray",
col.01line = "gray")
lines(ecdf(dta),col="gray",
col.points=c(
rep(c("gray","red"),20)))
##
EDIT: even easier (without the additional lines call) incorporating at the aditional parameters available for plot.stepfun directly:
# nonsense colors, just to illustrate the possibility to set further parameters:
? plot.stepfun # has many more parameters!!
plot(ecdf(dta), pch=19,
col="blue",
col.points=c(
rep(c("gray","red"),20)),
verticals=TRUE, col.vert="pink",
col.01line = "green")
Related
If you call function hist on r, you will note that the box that usually surrounds plotting region doesn't appear, instead, only rulers indicating plot scale appear on the bottom and on the left. If you use r a lot you may probably have noticed this already. my question is: there is some graphical parameter or workaround to make this happen on any other plot of basic r (like in a scatterplot, a line plot, a qq plot or whatever)?
The only parameter I found was axes, but setting it to FALSE makes it disappear not only the box, but also the rulers.
You are looking for box().
op <- par(mfrow=c(1, 2))
hist(mtcars$mpg, sub="w/o box")
hist(mtcars$mpg, sub="w/ box")
box() ## <-- this
par(op)
the answer is bty graphical parameter:
x= matrix(rnorm(100), ncol= 2)
plot(x, bty= 'n')
Purpose
Create scatter plot with third dimension and multiple colors.
First:
- 3rd dimension with another scale in contrast to y-axis
- create two colors (this is done using col, see code)
Sketch simulating the purpose:
Code
Two "containers" of points plotted in this way:
plot(1:3, c(3,3,3))
points(1:3, c(2,2,2), col="blue")
Another nice plotting is done by:
#install.packages("hexbin")
library(hexbin)
x <- 1:1000#rnorm(1000)
y <- 1500:501#rnorm(1000)
bin<-hexbin(x, y, xbins=50)
plot(bin, main="Hexagonal Binning")
But I do not know how to use hexbin (I do not understand the functionality). There are needed two colors which I do not know how to generate.
Questions
How to create the 3rd axis with other scaling than the y-axis?
Can I use ´hexbin´ to get the result?
For some reason, using points() does not work, but using plot() does work:
#Set margin on right side to be a bit larger
par(mar = c(5,4.5,4,5))
#Plot first set of data
plot(1:3, rep(3,3), ylim=c(-5,5), xlab="X-Axis", ylab="Y-Axis 1")
#Plot second set of data on different axis.
par(new=T)
plot(1:3, rep(5,3), ylim=c(-10,10), col="blue", xlab="", ylab="", axes=FALSE)
#Add numbers and labels to the second y-axis
mtext("Y-Axis 2",side=4,line=3)
axis(4, ylim=c(-10,10))
I have found that when I try to overlay multiple rasters using plot(...,add=T) if I try to overlay more than 3 rasters together the subsequent plot does not align the rasters properly.
My original intent was to create a categorical map of modeled landcover where the darkness of the color representing a cover class varied wrt the certainty in our model projection. To do this, I created a simple script that would loop through each cover class and plot it (e.g., forest, green color on map) using a color gradient from grey (low certainty forest prediction) to full cover color (e.g., dark green for areas are strongly predicted).
What I have found is that using this approach, after the 3rd cover is added to the plot, all subsequent rasters that are overlayed on the plot are arbitrarily misaligned. I have reversed the order of plotting of the cover classes and the same behavior is exhibited meaning it is not an issue with the individual cover class rasters. Even more puzzling in Rstudio, when I use the zoom button to closely inspect the final plot, the misalignment worsens.
Do you have any ideas of why this behavior exists? Most importantly, do you have any suggested solutions or workarounds?
The code and data on the link below has all of the behaviors described captured.
https://dl.dropboxusercontent.com/u/332961/r%20plot%20raster%20add%20issue.zip
Turn plot_gradient=F to see how if you just simply subset a same raster and add the subsets sequentially to the same plot you can replicate the issue. I have already tried setting the extent of the plot device plot(..., ext) but that did not work. I have also checked and the extent of each cover raster is the same.
Below is the figure of the misaligned cover classes. plotting to jpeg device will result in a similar image (i.e., this is not an issue of Rstudio rendering).
Strangely enough, if I zoom into the image using Rstudio, the misalignment is different
For comparison, this is how the covers should align correctly in the landscape
library(raster)
library(colorRamps)
raster_of_classes=raster("C:/r plot raster add issue/raster_of_classes.tif")
raster_of_certainty_of_classes=raster("C:/r plot raster add issue/raster_of_certainty_of_classes.tif")
endCols=c("darkorchid4", "darkorange3", "red3", "green4", "dodgerblue4") #colors to be used in gradients for each class
classes=unique(raster_of_classes)
minVal=cellStats(raster_of_certainty_of_classes, min)
tmp_i=1
addPlot=F
plot_gradient=F #this is for debug only
#classes=rev(classes) #turn this off and on to see how last 2 classes are mis aligned, regardless of plotting order
for (class in classes){
raster_class=raster_of_classes==class #create mask for individual class
raster_class[raster_class==0]=NA #remove 0s from mask so they to do not get plotted
if (plot_gradient){
raster_of_certainty_of_class=raster_of_certainty_of_classes*raster_class #apply class mask to certainty map
}else{
raster_of_certainty_of_class=raster_class #apply class mask to certainty map
}
endCol=endCols[tmp_i] #pick color for gradient
col5 <- colorRampPalette(c('grey50', endCol))
if (plot_gradient){
plot(raster_of_certainty_of_class,
col=col5(n=49), breaks=seq(minVal,1,length.out=50), #as uncertainty values range from 0 to 1 plot them with fixed range
useRaster=T, axes=FALSE, box=FALSE, add=addPlot, legend=F)
}else{
plot(raster_of_certainty_of_class,
col=endCol,
useRaster=T, axes=FALSE, box=FALSE, add=addPlot, legend=F)
}
tmp_i=tmp_i+1
addPlot=T #after plotting first class, all other classes are added
}
I had this problem too and solved it by calling the graphical parameters function, par(), with a subset of parameters, and most importantly, put the new=TRUE in the par() call, not the plot() call, before each additional plot() call. For example:
png(fullname,
width = 3000,
height= 3000)
# original par() call
par(mfrow=c(1,1), cex=3, mar=c(3,3,3,7), bg=bgcol, col=txtcol)
# first plot
plot(zreate,
maxpixels=ncell(zreate),
col=qcol,
colNA=mapbg,
xaxt='n',
yaxt='n',
ext=map_extent,
breaks=tq,
bty='n',
legend=FALSE)
#second plot and par() call
par(mfrow=c(1,1), cex=3, mar=c(3,3,3,7), bg=bgcol, col=txtcol, new=TRUE)
plot(rt,
maxpixels=ncell(rt),
col=dcol,
legend=FALSE,
xaxt='n',
yaxt='n',
ext=map_extent,
bty='n')
#third plot and par() call
par(mfrow=c(1,1), cex=3, mar=c(3,3,3,7), bg=bgcol, col=txtcol, new=TRUE)
plot(r0,
maxpixels=ncell(r0),
col="#9e9ac8",
xaxt='n',
yaxt='n',
ext=map_extent, #PRENAFILTERING fix
bty='n',
legend=FALSE)
In December 2013, I posted a question about exactly this behavior to the R-sig-geo mailing list, and got no useful response (other than a confirmation that it also happens with R versions and OS's different than my own).
Here, for the record, is the reproducible example that I used to illustrate the issue. (See the linked question for some more explanation.)
library(maptools) ## Only needs to be installed for example data
library(raster)
library(rgeos)
## Create an example raster
p <- shapefile(system.file("shapes/co37_d90.shp", package="maptools"))
p <- p[31,] ## A tall narrow county polygon
pr <- gDifference(gBuffer(p, width=.01), p)
r <- rasterize(pr, raster(extent(pr), ncol=100, nrow=100))
## These three are properly registered on one another
plot(r, col="yellow", legend=FALSE)
plot(r, col="green", legend=FALSE, add=TRUE)
plot(r, col="grey", legend=FALSE, add=TRUE)
## All subsequent "layers" are improperly shifted/skewed to right
plot(r, col="yellow", legend=FALSE, add=TRUE)
plot(r, col="blue", legend=FALSE, add=TRUE)
plot(r, col="red", legend=FALSE, add=TRUE)
plot(r, col="grey20", legend=FALSE, add=TRUE)
## Following the above, SpatialPolygons are also shifted/skewed
plot(p, border="red", lwd=2, add=TRUE)
I have run into the same problem and found an answer that is less of a hack than the previous answer. It follows the train of thought described by user "Dial".
The key is to use image(). But add in the argument maxpixels = ncell(x). This way, the resolution is maintained and pixel aggregation does not occur either as much or at all.
> x <- brick(image.path)
> plotRGB(x)
> image(brick.overlay, add = T, col = 'black', maxpixel = ncell(x))
> image(brick.overlay, add = T, col = 'yellow', maxpixel = ncell(x))
The "brick.overlay" would be some mask object, region of interest, or otherwise subsetted data where data is associated with those pixels and all other pixels are NA.
The brick.overlay object should have to have an implied extent based on total number of pixels where all non-interest pixels are NA.
This is hardly the most memory efficient way, but it's the one I know works.
If you use "Dial's" example, I think you would do:
image(r, col="yellow", add=TRUE, maxpixels = ncell(r))
Interesting problem. As you likely know, image() doesn't seem to have the same issue but generally makes uglier maps, right?
library(raster)
library(rgeos)
## Create an example raster
p <- shapefile(system.file("shapes/co37_d90.shp", package="maptools"))
p <- p[31,] ## A tall narrow county polygon
pr <- gDifference(gBuffer(p, width=.01), p)
r <- rasterize(pr, raster(extent(pr), ncol=100, nrow=100))
## These three are properly registered on one another
image(r, col="yellow")
image(r, col="green", add=TRUE)
image(r, col="grey", add=TRUE)
## All subsequent "layers" are also registered
image(r, col="yellow", add=TRUE)
image(r, col="blue", add=TRUE)
image(r, col="red", add=TRUE)
image(r, col="grey20", add=TRUE)
## Following the above, SpatialPolygons are no longer shifted/skewed
plot(p, border="red", lwd=2, add=TRUE)
Struggling with this one. I have 25 data items that I want plotted with bubbles in 5 columns.
The plot can be re-created thus:
xcord <- c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4,5,5,5,5,5)
ycord <- c(1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5)
zsize <- c(2,1,2,3,6,8,9,1,4,5,5,6,7,8,8,9,5,5,5,5,1,8,1,1,12)
Save the parameters before I change them:
op <- par()
dev.off()
Change the parameters:
par (mfrow=c(1,0), mar=c(2,2,2,2), oma=c(2,2,2,2))
Plot using symbols:
symbols(xcord, ycord, zsize, inches=0.3, fg="white", bg="red", xlab="Events", ylab="Diagnoses", tck=0, xaxt="n", yaxt="n")
mtext("Rheumatic diagnoses by cerebrovasular events", line=2, font=2, cex=1.2)
I am happy with the above plot and deliberately used tck=0, xaxt="n", yaxt="n" to clear the axes. I want to manually overlay custom text, controlled with custom co-ordinates (which work with the sysmbols plot), but have not been able to do it. I have tried some of the par arguments and the axes function.
I also tried leaving the axes on:
symbols(xcord, ycord, zsize, inches=0.3, fg="white", bg="red", xlab="Events", ylab="Diagnoses")
but do not know how to change the output (1,2,3,4,5) to my own custom axes labels.
Thank you.
You are looking for the axis function (see ?axis for details), e.g. to replace the 1:5 with A, B, C, D, E:
axis(side=1, at=1:5, labels=LETTERS[1:5])
Is there a way to set the background colour of a polygon? I want to get a plot like this...
set.seed(1)
n <- 100
xx <- c(0:n, n:0)
yy <- c(c(0,cumsum(stats::rnorm(n))), rev(c(0,cumsum(stats::rnorm(n)))))
plot (xx, yy, type="n", xlab="Time", ylab="Distance")
polygon(xx, yy, angle=45, density=10)
polygon(xx, yy+5, col="white")
polygon(xx, yy+5, angle=45, density=10, col="red")
But ideally without the penultimate line to set the background (I am plotting multiple polygons within a function I am writing). Is there an argument I can use in the final line that will negate the whole of the penultimate line? Cheers.
My answer is 'no' - help(polygon) gives you col for filling the polygon but also uses it for the line shading colour if using angle and density.
This is a relic of the old days when your pen plotter could only pick up one pen at at time...
Doing it twice shouldn't be a problem. Write your own function that takes a polygon and two colour parameters and calls polygon twice.