Plotting a box within filled.contour plots in R? - r

I'm trying to plot a box within a filled.contour plot, but unfortunately, when I plot the lines() after the filled.contour plot is created, the figure is shifted to the right because the scale forces the image to the left, but the box stays at the same coordinates. Here's what my code looks like:
dev.new(width=6,height=7)
mypredict<-matrix(data=mypredict,nrow=20,ncol=25)
filled.contour(x=seq(from=-1.5,to=1.5,length=20),
y=seq(from=1,to=3.75,length=25),
z=mypredict,
col=hsv(h=seq(from=2/3,to=0,length=20),s=1,v=1)
)
top <- 3.42
bot <- 1.56
lines(c(-1,-1),c(bot,top))
lines(c(1,1),c(bot,top))
lines(c(-1,1),c(top,top))
lines(c(-1,1),c(bot,bot))
Does anyone know how I can plot those lines within the filled.contour function? Otherwise, the lines do not plot correctly onto the main image, since the scale/legend of the graph is placed on the right.
Thanks!

The manual page for filled.contour explains the problem (and gives a solution)
This function currently uses the ‘layout’ function and so is restricted
to a full page display. As an alternative consider the ‘levelplot’
and ‘contourplot’ functions from the ‘lattice’ package which work in
multipanel displays.
The output produced by ‘filled.contour’ is actually a combination
of two plots; one is the filled contour and one is the legend.
Two separate coordinate systems are set up for these two plots,
but they are only used internally - once the function has returned
these coordinate systems are lost. If you want to annotate the
main contour plot, for example to add points, you can specify
graphics commands in the ‘plot.axes’ argument. An example is
given below.
So essentially you pass some instructions as the plot.axes parameters to override standard behaviour.
In your example:
filled.contour(x = seq(from=-1.5,to=1.5,length=20),
y = seq(from=1,to=3.75,length=25), z = mypredict,
col = hsv(h=seq(from=2/3,to=0,length=20),s=1,v=1),
plot.axes = {axis(1); axis(2); rect(left, bottom, right, top);})
Note that you have to recreate the two axes otherwise they will not be drawn. Also, no need to use the lines statement, when there is a rect function! :)
Hope this helps

Related

How to move the legend to outside the plotting area in Plots.jl (GR)?

I have the following plot where part of the data is being obscured by the legend:
using Plots; gr()
using StatPlots
groupedbar(rand(1:100,(10,10)),bar_position=:stack, label="item".*map(string,collect(1:10)))
I can see that using the "legend" attribute, the legend can be moved to various locations within the plotting area, for example:
groupedbar(rand(1:100,(10,10)),bar_position=:stack, label="item".*map(string,collect(1:10)),legend=:bottomright)
Is there any way of moving the plot legend completely outside the plotting area, for example to the right of the plot or below it? For these kinds of stacked bar plots there's really no good place for the legend inside the plot area. The only solution I've been able to come up with so far is to make some "fake" empty rows in the input data matrix to make space with some zeros, but that seems kind of hacky and will require some fiddling to get the right number of extra rows each time the plot is made:
groupedbar(vcat(rand(1:100,(10,10)),zeros(3,10)),bar_position=:stack, label="item".*map(string,collect(1:10)),legend=:bottomright)
I can see that at there was some kind of a solution proposed for pyplot, does anyone know of a similar solution for the GR backend? Another solution I could imagine - is there a way to save the legend itself to a different file so I can then put them back together in Inkscape?
This is now easily enabled with Plots.jl:
Example:
plot(rand(10), legend = :outertopleft)
Using layouts I can create a workaround making a fake plot with legend only.
using Plots
gr()
l = #layout [a{0.001h}; b c{0.13w}]
values = rand(1:100,(10,10))
p1 = groupedbar(values,bar_position=:stack, legend=:none)
p2 = groupedbar(values,bar_position=:stack, label="item".*map(string,collect(1:10)), grid=false, xlims=(20,3), showaxis=false)
p0=plot(title="Title",grid=false, showaxis=false)
plot(p0,p1,p2,layout=l)

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:

cluster: :clusplot axis in wrong direction

I'm trying to plot the cluster obtained from fuzzy c-means clustering.
The plot should look like this.
code for the plot
plot(data$Longitude, data$Latitude, main="Fuzzy C-Means",col=data$Revised, pch=16, cex=.6,
xlab="Longitude",ylab="Latitude")
library(maps)
map("state", add=T)
However, when I tried to use clusplot the plot is displaying in opposite direction(both top and bottom and left and right) as below.
I wanna know if there's a way to reverse the plot to show in the order as the above picture.
Also, for the very dense area, it's hard to find the ellipse label. I wanna know if there's a way to show the label inside the ellipse instead of outside.
code for 2nd pic
library(cluster)
clusplot(cbind(Geocode$Longitude, Geocode$Latitude), cluster, color=TRUE,shade=TRUE,
labels=4, lines=0,col.p=cluster,
xlab="Longitude",ylab="Latitude",cex=1)
clusplot is a function that performs a lot of magic for you. In particular it projects the data set - which happens in a way you don't like, unfortunately. (Also note the scales - it centered and scaled the data, too)
clusplot.default: Creates a bivariate plot visualizing a partition (clustering) of the data. All observation are represented by points in the plot, using principal components or multidimensional scaling.
As far as I can tell, clusplot doesn't have map support, but you will want such a map I guess...
While maybe you can use the s.x.2d parameter to specify the exact projection (and this way disable automatic scaling), it probably is still difficult to add the map. Maybe look at the source of clusplot instead, and take only the parts you want?

Control contour line transparency plot.kde

I'm using plot.kde in library(ks) to extract contour levels of kernel density plots. I'd like to overlay multiple plots so I'm making the contour fills semi-transparent. However, there is a border/contour line whose color I just can't seem to control.
I have tried changing all of the different col,cont.col,color (etc) options in the plot.kde function and just can't seem to hone in on the color of the contour itself. I could probably use some work around by extracting the coordinates of the contour from the kde object and then plotting this using the polygon() function, but I'd really like to control this from within plot.kde. It's something I'll be running many times.
This is likely super simple but I'm just missing it! In the figure below, it's the thicker red line I'm trying to control.
Thanks!!!
library(ks)
data(unicef)
H.scv <- Hscv(x=unicef)
fhat <- kde(x=unicef, H=H.scv, compute.cont=TRUE)
plot(fhat, display="filled.contour2", cont=c(10),col=c(NA,rgb(1,0,0,0.5)))

How to draw abline() that doesn't intersect the Y-axis in R?

I have a location quotient plot drawn in R and want to draw a horizontal line along the plot where Y = 1. I have the code abline(h=1, col="black") but when the line is drawn, it intersects the Y-axis and crosses out my Y-axis labels.
Does anyone know how to terminate the line at the Y-axis rather than having it intersect?
Many thanks.
As mentioned in the comments, it looks like the parameter xpd has been changed, so one option is to change it back to FALSE, see ?par. you can control the clipping region using the clip function to further limit the range that abline and other functions plot within. This may also be affected by you plotting device (different devices can deal with clipping differently).

Resources