Using transparency settings on a kernel plot, R - r

Hi I am trying to plot and overlay multiple kernel density estimates into a single plot (using KS library). Since I want to overlay multiple kernels I am "playing" with the transparency color settings so that the final plot is easier to understand. However, for some reason when I plot it, it shows a grid pattern with the color color/transparency filling which I don't know how to remove so that the color is all uniform...
These are the options that I use to export my plot as a PDF,
pdf(paste(database$species[1],".pdf",sep=""),width=11,height=8,paper="a4r",pointsize=15)
par(mfrow=c(1,1))
par(mar=c(5,4,4,3))
This is the code that I use to make the plot and overlay it with others,
# plot of KUD-Depth utilization
plot(ddhat.day,cont=c(95),lwd=1,add=F,display="filled.contour2",col=c(NA,"#8B000040"),xaxs="i",yaxs="i",
plot(ddhat.night,cont=c(95),lwd=1.5,add=TRUE,display="filled.contour2",col=c(NA,"#00008020"),
xlab="",ylab="",las=1,ann=F,bty="l",cex=0.6,yaxs="i",xaxs="i")
xlab="",ylab="",las=1,ann=F,bty="l",cex=0.6,xlim=c(0,max(dd[,1]+dd[,1]*0.6)),ylim=c(50,-10))
plot(ddhat.day,cont=c(50),add=T,display="filled.contour2",col=c(NA,"#FF000040"),lty=2,lwd=1,
xlab="",ylab="",cex=0.6)
plot(ddhat.night,cont=c(50),add=TRUE,display="filled.contour2",col=c(NA,"#00BFFF40"),lwd=1.5,
xlab="",ylab="",cex=0.6)
plot(ddhat.day,cont=c(0,0),drawpoints=TRUE,col="black",ptcol="grey15",cex=0.45,add=TRUE)
plot(ddhat.night,cont=c(0,0),drawpoints=TRUE,col="black",ptcol="grey15",cex=0.45,add=TRUE,pch=4)
dev.off()
If anybody has an idea why when I use this transparency option for color it shows a grid too and ho to remove it so it shows a smooth surface that would be fantastic!

You have a really weird way of specifying col. Instead of those NAs which I'm pretty sure aren't supposed to be there, try using the rgb function. It takes (at least) 4 arguments, which are the red, green, blue and alpha (transparency) channels, expressed as fractions.
col=rgb(0, 0, 0, 1) # black
col=rgb(0, 1, 1, .5) # green + blue = cyan, 50% opaque
col=rgb(1, 0, 0, .2) # red, 20% opaque = 80% transparent

This is a pretty old question but I thought I'd throw my response out there for future reference. The grid that you are seeing (if it's the grid I think you are referring to) is the result of creating a raster graphic in a pdf file. The pdf does a poor job of rendering the raster. If you want to make the grid (really thin white lines, right?) go away, try saving the file as a native raster file type (eg., jpeg(),tiff).
In most cases, outputting an R graphic as a pdf() works great because then you have a nice, scalable vector graphic for which you don't have to worry about resolution. However, when you create figures like an image plot sometimes it gets wonky (this only happens on my Mac though and not on my PC).
Some code below may illustrate. If you run the pdf version (on a mac) you will get the figure below. If you run the jpg version it will go away.
library(MASS)
library(ks)
data(iris)
fhat <- kde(x=iris[,1:2])
jpeg("test.jpg")
plot(fhat, display="filled.contour2", cont=seq(10,90,by=10))
dev.off()
pdf("test.pdf")
plot(fhat, display="filled.contour2", cont=seq(10,90,by=10))
dev.off()

Related

R igraph output vertice is not shown

I am using R igraph package to display gene networks. The plot on Rstudio is like this (I can't post image because I am new user and don't have enough reputation, sorry about that):
R igraph on preview
Now I want to draw this on file to clearly see the changes and there is always an issue on vertices near margin side like this:
part of output pdf file
My code is as follows`
pdf("graph.pdf",width = 20, height = 10)
par(mar = c(9,9,9,9))
plot(finalnet, edge.arrow.size=0.1, edge.curved=FALSE,vertex.size= 3, margin = -0.5)
dev.off()
Update: I have tried square layout and the problem persists, here is my plotting object and square plot.
square plot
rda file for my igraph object
Can anyone give me an suggestion how to solve this issue? To whole net is about 170 vertices but I don't know why it cannot be displayed on output file well. I have tried different plot options in mai, mar but this seems to fail.
The reason you are getting this behavior is because you are specifying margin in your plot call. margin=-0.5 is telling R to extend the plot 0.5 units past the graphics device dimensions, below are three examples:
Your original plotting call, notice the clipping
pdf("withMargin.pdf")
par(mar=c(9,9,9,9))
plot(g, margin=-0.5)
dev.off()
Without the call to par, problem still presists but now youuse the entire dimension of the graphics device.
png("withoutPar_Margin.png")
#par(mar=c(9,9,9,9))
plot(g, margin=-0.5)
dev.off()
Lastly, removing the margin in plot
png("withoutplotMargin.png")
par(mar=c(9,9,9,9))
plot(g)
dev.off()
You're specifying a rectangular size for what looks like a square object. Try a square size, as in
pdf("graph.pdf")
This will use the defaults, which are square.
But, it's hard to know for sure since you haven't given us the object to troubleshoot for you.

Color gradients in R in PDF and bitmap output

I am struggling to get a visually acceptable color gradient in R (see here for a detailed description of my particular case). The problem, in short, is that while output in the R window looks OK, PDFs show thin, white lines between segments used to generate the gradient.
n <- 100
cc <- colorRampPalette(c("red", "blue"))(n)
plot.new()
par(mar=rep(0,4))
sapply(1:n, function(i) rect((i-1)/n, 0, i/n, 1, col=cc[i], border=NA))
dev.copy2pdf(file="test.pdf")
Here is the result:
You can see the thin, white lines. Their positioning depends on the zoom, so I assume that they are an artifact of how the PDF is displayed. Here the same in another zoom:
Unfortunately, these lines are also visible on a printout. I guess the problem may be with how the coordinates in the PDF get rounded when the vector graphics is rendered to bitmap for display or printing.
A possible solution would be to use segments which overlap with each other. This is acceptable only for solid colors; unfortunately, I would like to use transparent colors in the gradients as well.
What can I do to make my output in PDF better?
This seems to be an issue purely due to the renderer. E.g.:
I don't believe there's anything you can change about the PDF to fundamentally fix the issue. In my case, Adobe Acrobat looked good at any zoom level except at very high zoom (I had to go to 3200% zoom to see white lines).
Also, Chrome and Microsoft Edge seemed to work well.
Have you tried this solution? The first rectangle will take a bigger space and the second will be plotted on the first one thus eliminating the white lines behind it. The pdf that Ive got does not show white lines
n <- 100
cc <- colorRampPalette(c("red", "blue"))(n)
plot.new()
par(mar=rep(0,4))
sapply(1:n, function(i) rect((i-1)/n, 0, (i + 1)/n, 1, col=cc[i], border=NA))
dev.copy2pdf(file="test.pdf")
This is zoomed in at 6400 percent

Save Filled Area of Polygon in R

I am plotting polygon in R and saving it.Problem, I am facing is that the whole plot is saved as png file but I want to save only the filled area in the polygon.
Is there a way for that ?
x<-c(0.000000000,0.010986328,0.006351471,-0.004634857)
y<-c(0.000000000,0.007232612,0.012841203,0.006199415)
file_name = paste("~/Downloads/Plot", ".png", sep="")
png(file_name,width=1280,height = 720,units="px",res=200)
plot(x,y,axes=FALSE,ylab='',xlab='')+polygon(x,y,col="#FF0000FF")
dev.off()
If you're drawing a monofigure plot (which is the default), then I believe there are three possible sources of spacing that can cause a plot element to not extend to the edges of the graphics device:
1: data coordinate limits that are larger than the extent of the plot element.
2: "internal spacing", which is best thought of as an expansion of the plot area that sits inside the margins.
3: margins. This is normally where axes, ticks, tick labels, axis labels, titles, and sometimes legends are drawn.
All of these sources of spacing can be eliminated with the following customizations:
1: set the xlim and ylim graphics parameters to perfectly fit the target plot element.
2: set xaxs='i',yaxs='i', which can be done with either a preemptive par() call or on the initial plot() call.
3: zero the margins with mar=c(0,0,0,0). This must be done with par() prior to the initial plot() call.
Example:
## generate data
pts <- data.frame(x=c(0.2,0.4,0.9,0.7),y=c(0.5,0.4,0.5,0.6));
## precompute plot parameters
xlim <- range(pts$x);
ylim <- range(pts$y);
## draw plot
par(mar=c(0,0,0,0));
plot(NA,xlim=xlim,ylim=ylim,xaxs='i',yaxs='i',axes=F,ann=F);
points(pts$x,pts$y,pch=21L);
polygon(pts$x,pts$y,col='red',pch=21L);
Multifigure plots can incur one additional source of spacing, namely outer margins, but it looks like that doesn't concern you for this problem. In any case, I'm pretty sure outer margins always default to zero anyway.
See par() for the relevant documentation.
It looks like I misunderstood the question. What you want is a transparent background, which is different from simply fitting the image size to the plot element.
You can use the png() function to set the background to be transparent by passing bg='transparent', as explained on the documentation page.
For example, here's my fitted image saved with a transparent background:
Note that not all image viewers will correctly detect and/or clearly depict the transparency of the background. I would highly recommend GIMP, which is basically a free Photoshop knockoff, albeit markedly lighter in features. GIMP depicts transparent regions as a kind of checkerboard of grey squares, which looks like this:

Wrong output size when plotting over an image in R

My goal is to read an image file in either the PNG or JPEG format and plot various data over said image and save it to disk.
I also want the image to take up all available space in the produced plot, no axes or labels or anything. I'm a bit concerned that this might be relevant to my problem.
Code example
Below is my current code that currently only tries to output the same image as you put in. Later I plan on plotting data points corresponding to coordinates over the image. I've used some sample code found here in order to remove the axes and be able to have the image in the background of the plot.
library(jpeg)
library(grid)
img <- readJPEG(system.file("img", "Rlogo.jpg", package="jpeg"),native=TRUE)
jpeg(filename = "Rlogo-2.jpg", width=100,height=76, quality = 100,res=299)
op<-par(mar=rep(0,4))
plot(0:100,type="n", axes="FALSE",ann="FALSE")
lim <- par()
rasterImage(img, lim$usr[1], lim$usr[3], lim$usr[2], lim$usr[4])
dev.off()
Example output
This is an example output of my above code in a comparison with the original image:
The image to the left is the original and the right one is the modified one. As you can see it seems as if the image I read and plot somehow is smaller than the original image and when saved to the original dimensions it appears blurred.
I've been pulling my hair over this one for hours and I don't seem to get anywhere. This is my first attempt to plot data over images and I'm aware of my lack of knowledge about how R represents images and I've mostly been using the basic graphics to do relatively simple plots before.
I'm currently considering doing this in Python instead but I'm afraid that'll come back and bite me when it comes to the actual plotting of the data.
I run R version 3.1.0 on x86_64 running Windows 7.
Just to summarize, since you already found the culprit, there are two issues present here:
Firstly, the blurring appears to be caused by the jpeg device on Windows. There is no such problem on Ubuntu Linux and it disappears if you use the Cairo-device instead, as you did already discover. Cairo-devices are great for pdf:s too since they embed all the fonts etc. making the figure look the same across platforms.
Secondly, R adds 4% extra margin to the x and y axes by default to prevent graphics from being chopped off near the edge of the plot area. It can be corrected by setting xaxs="i" and yaxs="i".
par(mfrow=1:2)
plot(1:5, 1:5) # Left
plot(1:5, 1:5, xaxs="i", yaxs="i") # Right
In your case the difference is subtle but still would cause everything to be slightly misaligned.

How to do a ridiculously wide plot

I have a long time series of 10000 observations that I want to visualize. The problem is, if I just plot it normally the time-dimension will be squished and none of the fine detail of the time-series that I want to visualize will be apparent. For example:
plot((sin(1:10000/100)+rnorm(10000)/5),type='l')
What I would like is to somehow plot the following together side by side in one gigantically long plot without using par(mfrow=c(1,100)). I then want to export this very wide plot and simply scroll across to vizualise the whole series.
plot((sin(1:10000/100)+rnorm(10000)/5)[1:100],type='l')
plot((sin(1:10000/100)+rnorm(10000)/5)[101:200],type='l')
plot((sin(1:10000/100)+rnorm(10000)/5)[201:300],type='l')
.....
Eventually I would like to have 3 or 4 of these gigantically wide plots on top of each other with a par(mfrow=c(4,1)).
I know that the answer has something to do with the pin setting in par, but I keep getting Error in plot.new() : plot region too large. I'm guessing this has something to do with the interaction of pin with the other par parameters
Bonus points are awarded if we can get the pixel height and width exactly right. It is preferable that the plot doesn't skip random pixels due to the export sizing being imperfect.
Further bonus points if the image can be encoded in a .html. and viewed this way
An alternative that you might consider is svg, which will produce something of better quality than png/jpeg in any case.
Something like
svg(width = 2000, height = 7)
par(mfrow=c(4,1), mar = c(4, 4, 0, 2))
for (i in 1:4){
plot((sin(1:10000/100)+rnorm(10000)/5),type='l',
bty = "l", xaxs = "i")
}
dev.off()
will produce a very wide plot, just over 1MB in size, which renders quite nicely in Chrome.
Note the width and height are in inches here.
P.S. svg also offers the potential for interactive graphics. Just seen a nice example allowing the user to select a region of a long time series to zoom in on, see Figure 22 in Dynamic and Interactive R Graphics for the Web: The gridSVG Package, a draft paper by Paul Murrell and Simon Potter.
It could be a Cairo-specific problem, or it could be a lack of RAM on your machine. The following code works fine for me on a Windows 7 machine with 8GB RAM.
png("wide.png", width = 1e5, height = 500)
plot((sin(1:10000/100)+rnorm(10000)/5),type='l')
dev.off()
If I change the width to 1e6 pixels, then R successfully creates the file (it took about a minute), but no image viewing software that I have available can display an image that large.
I would go on some alternative route. First of all, what exactly is the point of viewing the entire plot at hi-res? If you're searching for some sort of anomalies or irregularities, well, that's what data processing is for :-) . Think about something like finding allx > 3sigma, or doing an FFT, etc.
Next, if you really want to examine the whole thing by eye, how about writing some R-TclTK code or using dynamicGraph or iplots or zoom to produce an interactive graph that you can scroll thru "live."
ETA: IIRC RStudio has tools for interactive graph scrolling and zoom as well.

Resources